2016-08-15 95 views
2

我想呈現一個來自我的Vue實例的對象列表。每個對象應該使用一個組件,所以我把組件放入v-for-loop。但我得到的是list.titlelist.text而不是正確的值。VueJS - v-for內的組件

在v-for-loops中使用組件有特殊的方法嗎?

我發現這個thread in the Vue-Forum,但不知道如何使用它或如果它是正確的方式。

應用:

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

模板:

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

我的組件:

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

Vue公司-實例:

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

謝謝!

回答

8

你應該在參數前使用:然後通過動態道具:

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

從技術文檔:

一個常見的錯誤初學者往往使正試圖通過降低使用了一些語法:

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

但是,由於這是一個文字道具,其值作爲普通字符串「1」傳遞,而不是實際的數字。如果我們要傳承一個實際的JavaScript數量,我們需要使用動態語法,以作爲一個JavaScript表達式的值進行估算:

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

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