Vue监听js中的变量

//TestFun.js
const b = {zhihu: 0}
let a = new Proxy({}, {
    set: function (obj, prop, value) {
        obj[prop] = value;

        if (prop == 'zhihu') {
            // console.log("set " + prop + ": " + obj[prop]);
            let nnn = new MyClass()
            nnn.jjj(value)
            b.zhihu = value
            console.log('b:' + b.zhihu)
        }
        return true;
    }
});
export class MyClass {
    async inc(count) {
        for (let i = 0; i < 30; i++) {
            for (let j = 0; j < 30; j++) {
                count += i + j
            }
            a.zhihu = i
        }
        return count;
    }
    async jjj(value){
        // console.log(value)
        b.zhihu = Math.random()
        console.log(b.zhihu)
        // return value
    }
}

export{
    b
}
//main
import MyWorker from 'comlink-loader!../../TestFun'
import {b} from '../../TestFun.js'
    export default {
        data() {
            return {
                counter: 0,
                continuedCount: 0,
                value: {a:0},
                arr: []
            }
        },
        methods: {
            async countP1() {
                const inst = new MyWorker();
                const objj = await new inst.MyClass();
                await objj.jjj()
                console.log(b.zhihu)
            },
            async continuedCountP() {
                const count = this.continuedCount;
                const inst = new MyWorker();
                const obj = await new inst.MyClass();
                this.continuedCount = await obj.inc(count)
                this.value = await obj.jjj()
            }
        },
        watch: {
            counter(oldval, newval) {
                console.log(oldval + ',' + newval)
            },
            'value.a':{
                handler(val){
                    console.log("value:" + val)
                }
            },
            arr:{
                handler(val){
                    console.log(val)
                },
                // deep: true
            },
            'b.zhihu':{
                handler(val){
                    console.log(val)
                },
                deep: true
            },
        },
    }

想实现js文件中的某些变量发生变动后,会触发Vue页面中的相应事件。

如有大佬能够解答,非常感激!

用watch,你写了watch了啊,请问哪里有问题。。

触发事件 子向父 用emit ;父向子 用 broadcast

https://vuex.vuejs.org/zh/

这个是官方推荐的 状态存储方法。不建议使用自定义文件。因为可能写不对。

全局变量与控件本来就是绑定的啊,用compute事件,他就是监听变量变化的。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632