计算属性不重新计算

时间:2017-11-13 16:36:19

标签: vue.js vuejs2 computed-properties

我有一个表单,用户从3个不同的<select>标签中选择1个选项。我想将所选选项存储在数组中。所以,我认为使用计算属性是一个很好的例子。我尝试将item0,item1和item2设置为计算属性,然后将数组中的相应索引设置为从setter传递的值中检索的值:

var app = new Vue({
    el: '#vue-app',
    data: {
        items: []
    },
    computed: {
        item0: {
            get: function () {
                return this.items[0].id;
            },
            set: function (itemId) {
                this.items[0] = this.getItem(newValue);
                //update other values
            }
        },
        item1: {
            get: function () {
                return this.items[1].id;
            },
            set: function (itemId) {
                this.items[1] = this.getItem(newValue);
                //update other values
            }
        },
        item2: {
            get: function () {
                return this.items[2].id;
            },
            set: function (itemId) {
                this.items[2] = this.getItem(newValue);
                //update other values
            }
        }
    },
    methods: {
        getItem: function (itemId) {
            //...
        }
    }
});

但是,给出这样的模板:

<div id="vue-app">
    <span>{{item0}}</span><br/>
    <span>{{item1}}</span><br/>
    <span>{{item2}}</span><br/>
</div>

这些项目的文本永远不会更新。我在setter中设置了一个断点,我可以确认这些值确实正确设置了。但是,视图永远不会重新计算计算属性(即永远不会再次调用getter)。我知道计算属性使用缓存但是当底层数据发生变化时它不应该失效吗?如果没有,还有另一种方法来为属性指定getter和setter吗?

Codepen重新解决问题:https://codepen.io/anon/pen/OOgNMN

0 个答案:

没有答案