javascript - v-for 用于作为 props 传递的数组抛出错误
问题描述
我正在将一组对象从父级传递给子级,并使用 v-for 对其进行循环。它抛出“TypeError:无法读取未定义的属性'标题'”
我有 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>
解决方案
您需要将 Post 组件包装在一个 div 中,如下所示:
<template>
<div>
<div v-for="post in posts" class="hello">
{{post.title}}
</div>
</div>
</template>
模板应该只包含一个根元素。
你也不需要:在 v-for 之前,它也会抛出错误。
这里是工作小提琴。
推荐阅读
- asp.net - 将 TextBox 输入传递给 ContentPlaceHolder 中的变量
- jdbc - 在 voltdb 上使用 jdbc 查询的低吞吐量
- javascript - 如果日期是周末,则使用 javascript 更改颜色
- indexing - 使用 Postman 的 Google 索引 API
- c - C 程序不在 main() 中休眠
- java - 爪哇。尝试调整用户必须解锁程序中的锁并完成程序的尝试
- ms-access - MS Access:使用列表框从不同的 Access 数据库中选择和导入表
- python - 登录 Tornado 后如何重定向到原始 url
- python - 如何将 python3 用于 profantiy 编辑器迷你项目?
- python - “打桩”一个数组,通过求和折叠