vue watch问题,请大佬指教

80 阅读1分钟

变量初始值为false,给变量赋值true后,再赋值false,过程中无法触发watch监听

vue3vue2输出结果相同,以下为vue2版本

1. 监听loading的变化

export default {
    data() {
        return {
            loading: false,
        };
    },
    watch: {
        loading: {
            handler(val) {
                console.log(val);
            },
            immediate: true,
        },
    },
    created() {
        this.loading = true;
        // doing something
        this.loading = false;
    },
};

输出结果:

false

2. 给watch加上deep:true

export default {
    data() {
        return {
            loading: false,
        };
    },
    watch: {
        loading: {
            handler(val) {
                console.log(val);
            },
            immediate: true,
            deep: true
        },
    },
    created() {
        this.loading = true;
        // doing something
        this.loading = false;
    },
};

输出结果:

false
false

3. 加上settimeout

export default {
    data() {
        return {
            loading: false,
        };
    },
    watch: {
        loading: {
            handler(val) {
                console.log(val);
            },
            immediate: true,
            deep: true,
        },
    },
    created() {
        this.loading = true;
        // doing something
        setTimeout(() => {
            this.loading = false;
        });
    },
};

输出结果:

false
true
false

请教各位大佬这个问题的原理,以及除了setTimeout以外的其他处理办法