vuejs2: how can i destroy a watcher?

旧巷老猫 提交于 2020-05-15 02:40:27

问题


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 ;)


回答1:


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




回答2:


Here is an example:

<script>
export default {
  data() {
    return {
      employee: {
        teams: []
      },
      employeeTeamsWatcher: null,
    };
  },

  created() {
    this.employeeTeamsWatcher = this.$watch('employee.teams', (newVal, oldVal) => {
      this.setActiveTeamTabName();
    });
  },

  methods: {
    setActiveTeamTabName() {
      if (this.employee.teams.length) {
        // once you got your desired condition satisfied then unwatch by calling:
        this.employeeTeamsWatcher();
      }
    },
  },
};
</script>


来源:https://stackoverflow.com/questions/46987893/vuejs2-how-can-i-destroy-a-watcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!