VueJS - 在v-for中使用组件

9
我正在尝试从我的Vue实例中呈现一个对象列表。每个对象都应使用组件,因此我将组件放入v-for循环中。但是,我得到的只是list.titlelist.text,而不是正确的值。
在v-for循环中使用组件有特殊的方法吗?
我在Vue论坛中发现了这个线程,但不知道如何使用它或者这是否是正确的方法。
应用程序:
<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"},
            ...
        ]
    }
})

谢谢!

1个回答

14
你应该使用动态属性将它们传递给参数,使用:来表示。
<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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接