Vue的watch 更改对象的两个属性,为什么只触发了一次?


<template>
    <div>
        {{ msg }}
    </div>
</template>
<script>
export default {
    data() {
        return {
            queryObj: {
                attr1: '',
                attr2: '',
                attr3: '',
                attr4: ''
            },
            msg: ''
        }
    },
    watch: {
        queryObj: {
            handler() {
                this.msg += '<br>改变了'
            },
            deep: true
        }
    },
    mounted() {
        // 第一种情况
        this.queryObj.attr3 = '2021-03-13'
        this.queryObj.attr4 = '2021-03-14'
        // 第二种情况
        // this.queryObj.attr3 = '2021-03-13'
        // this.$nextTick(() => {
        //   this.queryObj.attr4 = '2021-03-14'
        // })
    }
}
</script>
第一种情况 页面只打印了1次
第二种情况 页面只打印了2次

因为同步情况下改变多次data,会被合并成一次来提交,所以第一种情况只会触发一次,第二种一个是同步改变,一个是异步改变,会触发多次

铁铁 能帮我解决一个问题不😓😓

watch里面监听的queryObj换成queryObj.attr3试试

换成:
handler(obj) {
if (obj.attr3 || obj.attr4){
obj.msg += '
改变了'
}

        }