Salvar
Salvar

Reputation: 11

VueJS: Error when looping through data array with component

New to VueJS, and trying to use v-for to loop through an array of objects and output the component multiple times, or really for as many objects as are in the array, but receiving the following error:

[Vue warn]: Property or method "posts" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in < Root>)

Code:

<section id="special-posts-container" class="container">

 <special-posts
      v-for="post in posts"
      :post="post"
      :key="post.id"
      :username="post.username"
      :content="post.content"
      :date="post.date">
  </special-posts>

</section>

Vue.component('special-posts', {
  template: `
    <div class="special-item-container">
      <div class="special-item special-name">{{username}}</div>
      <div class="special-item special-post">
        <a href="{{url}}">{{content}}</a>
      </div>
      <div class="special-item special-date">{{date}}</div>
    </div>`,
  data() {
    return {
      posts: [
        {
          id: 1,
          username: 'rusty',
          date: '03/11/18',
          content: 'Some interesting words.'
        },
        {
          id: 2,
          username: 'adelle',
          date: '03/12/18',
          content: 'Some uninteresting words.'
        }
      ]
    }
  }
})

const vm = new Vue({ 
  el: '#special-posts-container'
})

Upvotes: 1

Views: 752

Answers (1)

Neha
Neha

Reputation: 2271

you have not defined posts in your #special-posts-container Vue object. you are passing a variable to another component without declaring it in current Vue.

const vm = new Vue({ 
  el: '#special-posts-container'
  data:{ 
          *********define posts here ****
       posts: [
         {
           id: 1,
           username: 'rusty',
           date: '03/11/18',
           content: 'Some interesting words.'
         },
         {
           id: 2,
           username: 'adelle',
           date: '03/12/18',
           content: 'Some uninteresting words.'
         }
         ]
      }
  });

Upvotes: 2

Related Questions