How to create a VUE watcher that watches a variable outside of the VUE instance

Wed Jul 20, 2022 Share on:

During a recent project, I needed to update a VUE prop based on an event emitted by an external JS library. This presented quite the head scratch till I came across this awesome tidbit on Stack Overflow. Basically, you just need to make the global var reactive by declaring an observable object and then setting up a watcher in your VUE component. Then anytime time the global var is updated your watcher can do its thing.

/**
* Global Variable
*/
const globalVar = Vue.observable({
    whydoesitfeelike: ""
});
Object.defineProperty(Vue.prototype, '$globalVar', {
    get() {
        return globalVar.whydoesitfeelike;
    },
    set(value) {
        globalVar.whydoesitfeelike = value;
    }
});


/**
* Watcher in your VUE component
*/
watch: {
    '$globalVar'(newValue) {
        this.showMJToast(newValue);
        // You can also change the value of the global
        // var from your component with:
        // this.$globalVar = 'value;
    }
}


/**
* Update the globalVar using vue.set when an event occurs outside
* of your VUE app
*/
Vue.set(Vue.prototype, '$globalVar', 'sombodys watching me');