I'm trying to display a list from an array of data, but I get an error: cannot read property 'name' of undefined
.
HTML
<div id="list">
<myitems v-for="item in list" v-bind:my="item">
</div>
JavaScript
var items = Vue.component('myitems', {
props: ['my'],
template: `<li>{{my.name}} {{my.age}}</li>`
});
new items({
data: {
list: [
{name: 'myName', age: 25}
]
}
}).$mount("#list");
I think I can't match item in list
and props my
but I'm unsure of what to do.
I believe the problem is in your html. The <myitems>
tag should be inside the scope of the v-for
directive, so it should not be declared on the <myitems>
tag. Try something like this:
HTML
<div id="list" v-for="item in list" >
<myitems v-bind:my="item"></myitems>
</div>
Okay, there are many issues in your code.
First thing - you have not defined the root Vue instance, should be like this:
new Vue({
data: {
list: [
{name: 'myName', age: 25}
]
}
}).$mount("#list");
Your component registation is good, keep It like that:
var items = Vue.component('myitems', {
props: ['my'],
template: `<li>{{my.name}} {{my.age}}</li>`
});
And you forgot to wrap your component into the ul
since template returns a li
<div id="list">
<ul>
<myitems v-for="item in list" v-bind:my="item"></myitems>
</ul>
</div>
Working example: https://jsfiddle.net/am5Ldp9k/
You have several issues in your code. First of all, you don't need to assign a variable to Vue components that you register. They will simply be available to you after you register them with Vue.component
:
Vue.component('myitems', {
props: ['my'],
template: '<li>{{my.name}} {{my.age}}</li>'
});
Second, you need a root component. You can do this by calling new Vue()
:
new Vue({
el: '#list',
data: {
list: [{ name: 'myName', age: 25 }]
}
});
You need to pass in an element ID/class to serve as the root element, and any data you want to pass down to the child elements. Once you do this, it should work properly. Here's a jsfiddle for a working example: https://jsfiddle.net/coligo/49gptnad/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.