How to monitor multiple variables at the same time in vue

There are two solutions:

   Way 1: Through calculated properties

   Method 2: Complete monitoring through $watch

Method 1: Calculated attribute (computed):

 data() {
                return {
                    num1: 10,
                    num2: 20,
                    num3: 30,
                    num4: 40,
                    msg: "msg",
                }
            },
            computed: {
                sum() {
                    return this.num1 + this.num2
                }
            },
            watch: {
                sum(nv, ov) {
                    console.log("num1+num2求和结果变化:", nv, ov);
                }
            },

Method 2: ($watch):

 data() {
                return {
                    num1: 10,
                    num2: 20,
                    num3: 30,
                    num4: 40,
                    msg: "msg",
                }
            },
            computed: {
                sum() {
                    return this.num1 + this.num2
                }
            },
            watch: {
                sum(nv, ov) {
                    console.log("num1+num2求和结果变化:", nv, ov);
                }
            },
            methods: {
                addWatch() {
                    // 在应用根属性上添加一个用于中转,但不需要劫持的变量数据 - 为其他区域提供调用支持
                    //      这种中转数据变量 在vue 开发规范中建议 以 $ 开头,实现和普通劫持变量的区分
                    if(this.$unwatch) return;
                    this.$unwatch = this.$watch("msg", (nv, ov) => {
                        console.log("$watch 监控的msg发生变化", nv, ov);
                    })
                    console.log(this.$unwatch);
                    console.log(this);
                },
                removeWatch(){
                    if(!this.$unwatch) return;
                    this.$unwatch();
                    this.$unwatch = undefined;
                },
                addNumWatch() {
                    this.$watch(
                        () => {
                            // return this.num3+this.num4
                            // return [this.num3,this.num4]
                            return {
                                num3:this.num3,
                                num4:this.num4
                            }
                        },
                        (nv, ov) => {
                            // console.log("$watch 监控的num3+num4发生变化", nv, ov);
                            // console.log("$watch 监控的[num3,num4]发生变化", nv, ov);
                            console.log("$watch 监控的{num3,num4}发生变化", nv, ov);

                        }
                    )
                }

Guess you like

Origin blog.csdn.net/SYQ15544423296/article/details/126769808