12

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

Gregor Voinov
  • 2,203
  • 7
  • 34
  • 52
  • How about an `if/else` inside the watcher, which is accessing a data attribute? – ssc-hrep3 Oct 28 '17 at 09:45
  • yeah at the moment i was doing it with a second property "loaded", which i turned true when the ajax call was done // child watch: { loaded: function(){ this.sortBy(); }, }, //parent photosApi.getGalleries(this.id).then((response) => { this.loaded = true; this.data = response.data; }).catch((error) => { because the data object gets later modified and then it shouldn't invoke the "sortBy" function – Gregor Voinov Oct 28 '17 at 14:33

3 Answers3

30

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

pate
  • 4,937
  • 1
  • 19
  • 25
5

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>
Syed
  • 15,657
  • 13
  • 120
  • 154
3

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

SeyyedKhandon
  • 5,197
  • 8
  • 37
  • 68