VueJS 如何在 v-for 中使用计算属性 [英] VueJS How can I use computed property with v-for

查看:122
本文介绍了VueJS 如何在 v-for 中使用计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在列表中使用计算属性.我使用的是 VueJS v2.0.2.

这是 HTML:

<p v-for="项目中的项目"><span>{{fullName}}</span></p>

这是Vue代码:

var items = [{ id:1, firstname:'John', lastname: 'Doe' },{ id:2, firstname:'Martin', lastname: 'Bust' }];var vm = new Vue({el: '#el',数据:{项目:项目},计算:{全名:功能(项目){返回 item.firstname + ' ' + item.lastname;},},});

解决方案

您无法为每次迭代创建计算属性.理想情况下,这些 items 中的每一个都是它们自己的 组件,因此每个组件都可以拥有自己的 fullName 计算属性.

如果您不想创建 user 组件,您可以做的是使用方法.您可以将 fullNamecomputed 属性移动到 methods,然后您可以像这样使用它:

{{ fullName(user) }}

另外,请注意,如果您发现自己需要将参数传递给 computed,您可能需要一个方法.

How can I use computed property in lists. I am using VueJS v2.0.2.

Here's the HTML:

<div id="el">
    <p v-for="item in items">
        <span>{{fullName}}</span>
    </p>
</div>

Here's the Vue code:

var items = [
    { id:1, firstname:'John', lastname: 'Doe' },
    { id:2, firstname:'Martin', lastname: 'Bust' }
];

var vm = new Vue({
    el: '#el',
    data: { items: items },
    computed: {
        fullName: function(item) {
            return item.firstname + ' ' + item.lastname;
        },
    },
});

解决方案

You can't create a computed property for each iteration. Ideally, each of those items would be their own component so each one can have its own fullName computed property.

What you can do, if you don't want to create a user component, is use a method instead. You can move fullName right from the computed property to methods, then you can use it like:

{{ fullName(user) }}

Also, side note, if you find yourself needing to pass an arguments to a computed you likely want a method instead.

这篇关于VueJS 如何在 v-for 中使用计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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