我正在将一系列对象从父对象传递到子对象,并使用v-for在其上循环。它将引发“ TypeError:无法读取未定义的属性'title'”
我以postsList作为父级,而Post作为子级。
代码框的链接:https://codesandbox.io/s/vue-template-hh0hi
如何进行这项工作?
// Parent
<template>
<div class="hello">
<Post :posts="posts"/>
</div>
</template>
<script>
import Post from './Post'
export default {
name: "PostsList",
data: () => {
return {
posts: [
{ title: 'one', description: 'desc one'},
{ title: 'two', description: 'desc two'}
]
}
},
components: {
Post
},
props: {
msg: String
}
};
</script>
Child
<template>
<div :v-for="post in posts" class="hello">
{{post.title}}
</div>
</template>
<script>
export default {
name: "Post",
props: {
title: { type: String, default: 'asdff' },
posts: {
type: Array,
default: () => []
}
}
};
</script>
答案 0 :(得分:4)
您需要像这样将POST组件包装在一个div中:
<template>
<div>
<div v-for="post in posts" class="hello">
{{post.title}}
</div>
</div>
</template>
模板应仅包含一个根元素。
您也不需要:在v-for之前,它也会引发错误。
HERE正在演奏。
答案 1 :(得分:2)
v-for
不需要冒号。实际上,添加冒号将导致vue尝试评估表达式,就好像post
是组件的属性一样,因此控制台中关于post
被使用但未注册为反应性。
此外,控制台中还有其他错误消息,涉及在根元素中使用v-for
时不应忽略。您需要将它们包装在另一个元素或另一个<template>
标签中,因为一个组件只能包含一个根元素。