美文网首页深入vue技术栈
vue中检测不到数组变化的解决方案

vue中检测不到数组变化的解决方案

作者: IOneStar | 来源:发表于2018-01-17 20:40 被阅读258次

    首次发表在个人博客

    数组中当你利用索引设置一个项时,发现视图不发生变化

    场景:

    最近做一个功能,要根据数组的index去修改对应项的isSave字段;

    data() {
        return {
            arr: [
                {
                    name: '测试1',
                    id: 1,
                    isSave: false,
                },
                {
                    name: '测试2',
                    id: 2,
                    isSave: false,
                },
            ],
        };
    }
    

    通过

    changeStatus(index) {
        this.arr[index].isSave = !this.arr[index].isSave;
    }
    

    最后视图并没有更新;

    详解

    查了一下官方文档关于列表渲染的注意事项讲解;

    由于javascript的限制,Vue不能检测一下变动的数组

    1.当你利用索引设置一个项时, 例如: vm.items[indexOfItem] = newValue;
    2.当你修改数组的长度时,例如: vm.items.length = newLength;

    为了解决第一类问题,一下方式都可以实现和 vm.items[indexOfItem] = newValue相同的效果,同时也将触发状态更新;

    Vue.set(example1.item, indexOfItem, newValue);
    
    
    example1.items.splice(indexOfItem, 1, newValue);
    

    为解决第二类问题,你可以使用splice:

    example1.items.splice(newLength)
    

    解决方法

    changeStatus(index) {
        const obj = this.ticketWatcher.goodVos[index];
        obj.isSave = !obj.isSave;
        this.$set(this.ticketWatcher, index, obj);
    }
      
    

    参考文档

    相关文章

      网友评论

      • 大山的那边:操作数组或者数组对象只能按照官方给的数组api,或者set

      本文标题:vue中检测不到数组变化的解决方案

      本文链接:https://www.haomeiwen.com/subject/mgtpoxtx.html