Passing a global var to a vue component attribute

2020-03-30 01:41发布

I'm trying to pass php/laravel data to my component from a custom global variable. I've seen examples of this going into the new Vue({}) area directly but I haven't seen any way to pass this by going into right into the component

<script>
var itemData = //json object
</script>

<custom-component item-data="ITEMDATAVAR"></custom-component>

I should specify that I do have item-data in my component props. The issue is that I'm not sure how to tell my component's html that I'm passing the value of the variable itemData and not the string "itemData"

3条回答
倾城 Initia
2楼-- · 2020-03-30 01:47

I think you are referring to dynamic props

<custom-component v-bind:item-data="ITEMDATAVAR"></custom-component>

or use the shorthand syntax

<custom-component :item-data="ITEMDATAVAR"></custom-component>
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-30 01:49

You should add the item-data to the props array like this:

Vue.component('custom-component', {

  props: ['item-data'],

  ...

}
查看更多
Anthone
4楼-- · 2020-03-30 02:06

You can research this Vue.js example

Create a variable

new Vue({
    el: '#el',
    data: yourJsonObject
})

In you component you have to write about props

Vue.component('custom-component', {
    props: ['item-data']
    ...
}

Pass the data to the component the same way

<custom-component item-data="ITEMDATAVAR"></custom-component>

I have not tested how it will work, guided by the documentation.

查看更多
登录 后发表回答