Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - Component inside of v-for

I am trying to render a list of objects from my Vue-Instance. Each object should use a component, so I put the component into the v-for-loop. But all I get is list.title and list.text instead of the correct values.

Is there a special way to use components in v-for-loops?

I found this thread in the Vue-Forum, but don't know how to use it or if it's the right way.

App:

<div id="app">
    <div v-for="list in lists">
        <listcard title="list.title" text="list.text"></listcard>
    </div>
</div>

Template:

<template id="listcard-template">
    <div class="card">
        <h2>{{ title }}</h2>
        <p>{{ text }}</p>
    </div>
</template>

My component:

Vue.component('listcard', {
    template: '#listcard-template',
    props: ['title', 'text']
})

Vue-Instance:

new Vue({
    el: "#app",
    data: {
        lists: [
            {title: "title1", text: "text1"},
            {title: "title2", text: "text2"},
            ...
        ]
    }
})

Thanks!

like image 919
Brotzka Avatar asked Aug 15 '16 07:08

Brotzka


People also ask

What is the key in V for?

The purpose of this key attribute is to give "a hint for Vue's virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list" (from Vue. js Docs). Essentially, it helps Vue identify what's changed and what hasn't.

What is V for in Vue?

v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data.

What are the 3 parts of a component in Vue?

Components in Vue are composed of three parts; a template (which is like HTML), styles and JavaScript. These can be split into multiple files or the same .

What is a recursive component Vue?

A Vue component is considered recursive if it references itself within its own template.


1 Answers

You should pass then as dynamic prop using : in front of parameters:

<listcard :title=list.title :text=list.text></listcard>

From documentation:

A common mistake beginners tend to make is attempting to pass down a number using the literal syntax:

<!-- this passes down a plain string "1" -->
<comp some-prop="1"></comp>

However, since this is a literal prop, its value is passed down as a plain string "1", instead of an actual number. If we want to pass down an actual JavaScript number, we need to use the dynamic syntax to make its value be evaluated as a JavaScript expression:

<!-- this passes down an actual number -->
<comp :some-prop="1"></comp>

https://vuejs.org/guide/components.html#Literal-vs-Dynamic

like image 81
Bogdan Kuštan Avatar answered Oct 05 '22 23:10

Bogdan Kuštan