首页 > 解决方案 > 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>

标签: javascriptvue.jsvue-component

解决方案


您需要将 Post 组件包装在一个 div 中,如下所示:

<template>
   <div>
      <div v-for="post in posts" class="hello">
         {{post.title}}
      </div>
   </div>
</template>

模板应该只包含一个根元素。

你也不需要:在 v-for 之前,它也会抛出错误。

这里是工作小提琴。


推荐阅读