Vuejs2 - 组件中的计算属性

时间:2016-11-03 14:06:34

标签: computed-properties vuejs2

我有一个显示名称的组件。我需要计算每个名字的字母数。 我将nameLength添加为计算属性,但vuejs不会在循环中确定此属性。

var listing = Vue.extend({
    template: '#users-template',
    data: function () {
        return {
            query: '',
            list: [],
            user: '',
        }
    },
    computed: {
        computedList: function () {
            var vm = this;
            return this.list.filter(function (item) {
                return item.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1
            })
        },
        nameLength: function () {
            return this.length; //calculate length of current item
        }
    },
    created: function () {
        this.loadItems();
    },
    methods: {
        loadItems: function () {
            this.list = ['mike','arnold','tony']
        },
    }
});

http://jsfiddle.net/apokjqxx/22/

预期结果

话筒-4

阿诺德-6

托尼-4

1 个答案:

答案 0 :(得分:0)

似乎对计算属性存在一些误解。 我已经从你的小提琴中创建了一个叉子,它可以根据你的需要工作。

http://jsfiddle.net/6vhjq11v/5/

nameLength: function () {
    return this.length; //calculate length of current item
}

在评论中显示"计算当前项目的长度" 但是js无法获得当前项目的概念

this.length

这将在Vue组件上执行长度,而不是该值。

计算属性在实例的其他属性上工作并返回值。

但是在这里你没有指定任何内容并使用它,所以它不能使用任何属性。

如果您需要更多信息,请发表评论。