Search code examples
vuejs2watchdestroy

vuejs2: how can i destroy a watcher?


How can i destroy this watcher? I need it only one time in my child component, when my async data has loaded from the parent component.

export default {
    ...
    watch: {
        data: function(){
            this.sortBy();
        },
    },
    ...
}

gregor ;)


Solution

  • If you construct a watcher dynamically by calling vm.$watch function, it returns a function that may be called at a later point in time to disable (remove) that particular watcher.

    Don't put the watcher statically in the component, as in your code, but do something like:

    created() {
       var unwatch = this.$watch(....)
       // now the watcher is watching and you can disable it
       // by calling unwatch() somewhere else; 
       // you can store the unwatch function to a variable in the data
       // or whatever suits you best 
    } 
    

    More thorough explanation may be found from here: https://codingexplained.com/coding/front-end/vue-js/adding-removing-watchers-dynamically