【问题标题】:Vuejs2 - computed property in componentsVuejs2 - 组件中的计算属性
【发布时间】:2016-11-03 14:06:34
【问题描述】:

我有一个显示名称的组件。我需要计算每个名字的字母数。 我添加了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

tony-4

【问题讨论】:

    标签: computed-properties vuejs2


    【解决方案1】:

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

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

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

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

    this.length
    

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

    计算属性作用于实例的其他属性和返回值。

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

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

    【讨论】:

    • 感谢 Hardik,但您的 jsfiddle 示例不起作用。
    • jsfiddle.net/6vhjq11v/5 试试这个,抱歉忘记更新了
    • 谢谢,如果将计算长度移动到可以按预期正常工作的方法。如果存在一种使用计算的方法,那就很有趣了。示例 vuejs.org/guide/computed.html#Computed-vs-Watched-Property 计算 FullName....
    • 你是对的,但你可以看到它正在使用模型值,在我们的例子中,我们正在使用这个......你可以计算但你需要特定的模态/变量
    • 感谢您的澄清。下一步是找到使方法可重用于其他组件的方法:)
    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 2019-04-24
    • 2018-07-11
    • 2020-04-12
    • 2018-01-22
    • 2018-02-07
    • 2019-03-31
    • 2018-11-27
    相关资源
    最近更新 更多