美文网首页
vue实现监听多维数组和深度监听对象的方式

vue实现监听多维数组和深度监听对象的方式

作者: 李牧敲代码 | 来源:发表于2019-01-21 21:21 被阅读0次

使用vue的过程中,如果数组或对象发生了变化,vue是监听不到的,这里总结下对多维数组和多层对象的监听。

监听多维数组:

方法: Vue.set
例子:

<template>
    <div>
        {{arr}}
        <button @click = "testAdd">add 1</button>
    </div>
</template>
<script>
    export default {
        name: 'test',
        inheritAttrs: false,
        props: ['msg'],
        data() {
            return {
                arr: [1, 23, [1, 2]]
            }
        },
        methods: {
            testAdd() {
                this.arr[2][0] ++;
                this.$set(this.arr[2], 0, this.arr[2][0]);
            }
        }
    }
</script>

思路就是一层一层监听,这样既可以监听多维数组了,这个方法同样适用对象或者,但是对对象的监听个人觉得下面方法更好

监听深层对象:

方法: Vue.watch
例子:

<template>
    <div>
        {{obj}}
        <button @click = "testAdd">add 1</button>
    </div>
</template>
<script>
    export default {
        name: 'test',
        inheritAttrs: false,
        props: ['msg'],
        data() {
            return {
                obj: {
                    a: 100,
                    b: {
                        b1: 200
                    }
                }
            }
        },
        methods: {
            testAdd() {
                this.obj.a ++;
            }
        },
        watch: {
            obj: {
                handler(newValue, oldValue) {
                    console.log('newValue', newValue);
                    console.log('oldValue', oldValue);
                },
                deep: true
            }
        }
    }
</script>

(完)

相关文章

网友评论

      本文标题:vue实现监听多维数组和深度监听对象的方式

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