Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 621
Gregor Voinov Avatar asked Oct 28 '17 08:10

Gregor Voinov


3 Answers

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

like image 121
pate Avatar answered Oct 23 '22 19:10

pate


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>
like image 4
Syed Avatar answered Oct 23 '22 21:10

Syed


If you are using vue2 using the composition-api plugin or vue3, you can use WatchStopHandle which is returned by watch e.g.:

    const x = ref(0);

    setInterval(() => {
      x.value++;
    }, 1000);

    const unwatch = watch(
      () => x.value,
      () => {
        console.log(x.value);
        x.value++;

        // stop watch:
        if (x.value > 3) unwatch();
      }
    );

For this kind of stuff, you can investigate the type declaration of the API, which is very helpful, just hover the mouse on it, and it will show you a hint about what you can do: enter image description here

like image 2
SeyyedKhandon Avatar answered Oct 23 '22 20:10

SeyyedKhandon