v-for for array passed as props throws error

Viewed 381

I am passing an array of objects from parent to child and loop over it using v-for. It throws "TypeError: Cannot read property 'title' of undefined"

I have postsList as parent and Post as the child.

Link for codesandbox: https://codesandbox.io/s/vue-template-hh0hi

How to make this work?


// 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>
2 Answers

You need to wrap your Post component in one div like this:

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

Template should contain only one root element.

Also you do not need : before v-for, it will throw error also.

HERE is working fiddle.

v-for doesn't need the colon. In fact, adding the colon will lead to vue trying to evaluate the expression as if post were a property of the component, hence the other error message in the console about post being used but not registered as a reactive property.

Also, there are other error messages in the console about using v-for in the root element that you shouldn't ignore. You need to wrap them in another element or another <template> tag, as a component may only consist of one root element.

Related