VueJS - v-for内部的组件 [英] VueJS - Component inside of v-for

查看:78
本文介绍了VueJS - v-for内部的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的Vue-Instance渲染对象列表。每个对象都应该使用一个组件,因此我将组件放入v-for-loop中。但我得到的只是 list.title list.text 而不是正确的值。

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.

有没有一种特殊的方法可以在v-for-loops中使用组件?

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

我发现这个 Vue-Forum中的主题,但不知道如何使用它或者它是否是正确的方式。

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

应用程序:

<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-Instance:

Vue-Instance:

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

谢谢!

推荐答案

您应该在参数前使用作为动态道具传递:

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

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

来自文档:


初学者倾向于犯的一个常见错误是尝试使用文字语法传递一个数字:

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>




但是,因为这是一个文字道具,所以它的值传递下来作为普通字符串1,而不是实际数字。如果我们想传递一个实际的JavaScript数字,我们需要使用动态语法将其值评估为JavaScript表达式:

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

这篇关于VueJS - v-for内部的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆