Lukas
Lukas

Reputation: 7734

Pass data object to component from Vue for loop

So i have some object with posts, and i'm using v-for to iterate them in the custom component, but how to pass data from this object to this component, loop is a one thing displaying data i another...

<app-single-post v-for="post in posts" postData="$post"></app-single-post>

This is my component declaration. Do i need also some kind of special prop setup? Have the same error, again and again:

Property or method "postData" is not defined

Upvotes: 2

Views: 3995

Answers (1)

Bert
Bert

Reputation: 82499

Use the binding syntax.

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

Camel-cased properties need to be converted to kebab-case when they are used as attributes. Also, I added a key. You should always use a key when you use v-for and it is required when you iterate over a custom component. Ideally you would want to use a post.id if one is available.

In your component, you should have a property defined like this:

export default {
    props:["post"],
    methods: {...},
    etc.
}

To reference the post in your component template you can use

 {{post.id}}

and inside methods it would be

this.post

Upvotes: 10

Related Questions