gpt4 book ai didi

javascript - v-for for 作为 props 传递的数组会引发错误

转载 作者:行者123 更新时间:2023-12-02 21:04:30 25 4
gpt4 key购买 nike

我将一个对象数组从父级传递给子级,并使用 v-for 对其进行循环。它抛出“TypeError:无法读取未定义的属性‘标题’”

我将 postsList 作为父级,将 Post 作为子级。

codesandbox 链接: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 之前,它也会抛出错误。

HERE正在拉 fiddle 。

关于javascript - v-for for 作为 props 传递的数组会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com