Reputation: 1245
I get my data via AJAX from the Vue instance, and I need to pass that data to the components. I am now learning how Vue.js works, but I find the documentation a little fragmentary...
Here is aproximately my code:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>mysite</title>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
<template id="parent-component-template">
<div id="the-template">
<div class="the-list">
<span is="sector-item" v-for="item in sectors" :sector="item"></span>
</div>
<button>Button</button>
</div>
</template>
<template id="sector-item-template">
<span>
{{ sector.name }}
</span>
</template>
<!-- Vue.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script>
Vue.component('parent-component', {
template: '#parent-component-template'
});
Vue.component('sector-item', {
props: ['sector'],
template: '#sector-item-template'
});
let app = new Vue({
el: '#app',
data: {
sectors: [{
'id': 1,
'name': 'Industry'
}]
}
});
</script>
</body>
</html>
I get the following error:
[Vue warn]: Property or method "sectors" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
Where do I make a mistake?
Upvotes: 1
Views: 3334
Reputation: 743
I think your code is not complete. I tried to simulate what you trying to, in the snippet bellow:
Vue.component('parent-component', {
props: ['sectors']
});
Vue.component('child-component', {
props: ['item']
});
new Vue({
el: '#app',
data: {
sectors: [
{
'id': 1,
'name': 'Industry'
},
{
'id': 2,
'name': 'Education'
}
]
}
});
.the-list > div {
padding: 5px;
border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<parent-component :sectors="sectors" inline-template>
<div class="the-list">
<child-component :item="sector" :key="sector.id" v-for="sector in sectors" inline-template>
<div>
<span v-text="item.name"></span>
<button>Button</button>
</div>
</child-component>
</div>
</parent-component>
</div>
The Vue instance owns the property sectors
and I passed this property as a prop
to the <parent-component>
.
Now <parent-component>
has a prop called sectors
(it could be another name) that received the value of sectors
from the main Vue instance. I've used v-for
to iterate over all items of the parent-component prop passing each item of the array to the <child-component>
.
The <child-component>
has a prop called item
in which I passed the value of each element of the array.
You can learn more, here for free.
I hope this answer can be helpful.
Upvotes: 1