[Vuejs]-Using component with one props

0👍

props:[‘post’] check this plural. I figure that you are passing an array of posts to the component, and inside that component iterate over it.

0👍

You need top pass data.

Vue.component('blog-post', {
    props:['post'],
    template:`
    <div class="blog-post">
    <h3>{{ post.title }}</h3>
  </div>  
    `
})
new Vue({
    el : '#app',
    data: {
        posts: [
            {
                title:  'post-1' 
            },
            {
                title:  'post-2' 
            },
            {
                title:  'post-2' 
            }   
        ]
    }
})

so now

<blog-post
    v-for="post in posts"
    v-bind:key="post.id"
    v-bind:post="post"
></blog-post>

you can use v-for and it will take posts data and iterate through it and pass single post to the component and component will use that property and render html.

here when blog-post will receive post it will be this [ v-bind:post=”post” ]

{
    title:  'post-1' 
}

and it will use its post.title

v-for it will iterate this blog-post component [in our case 3 times] and pass each post object which is in array as post property of blog-post component.

if any doubts please comment.

0👍

Not sure I understand the question but I’ll try to help:

  1. The reason you get the error is because you are looping posts, but you haven’t defined them anywhere, so you need to change your main instance data:

    new Vue({
        el : '#app',
        data: {
           posts: [{author: "someone", text: "something", title: "Some post"}]
        }
    })
    
  2. There is a shorthand for v-bind, so instead you can write:

    <div id="app">
            <blog-post
            v-for="post in posts"
            :key="post.id"
            :post="post"
          ></blog-post>
    </div>
    

Leave a comment