本文介绍了vuejs2:如何销毁观察者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能摧毁这个观察者?当我的异步数据从父组件加载时,我只在我的子组件中需要它一次.

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();
        },
    },
    ...
}

格雷戈 ;)

推荐答案

如果通过调用 vm.$watch 函数动态构造观察者,它会返回一个函数,该函数可能会在稍后的时间点被调用以禁用(移除)那个特定的观察者.

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
}

更详尽的解释可以从这里找到:https://codingexplained.com/coding/front-end/vue-js/adding-removing-watchers-dynamically

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

这篇关于vuejs2:如何销毁观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:14