Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initiate a watcher only after a page has loaded.

Tags:

vue.js

vuejs2

I have a watcher that call a method like

watch: {
  'list.items' (n, o) {
     this.doSomething()
   }
}

The thing is, whenever the page loads, I push new values into list.items as:

methods: {
  fetchLists(){
    axios.get('/').then(
      res =>  {
       this.items.push(res.data) 
    };
  }
}

And I call fetchLists in created as:

created () {
  this.fetchLists()
}

The issue here is the watcher calls this.doSomething() when the page loads since list.items changes, but I wan't the watcher to only call doSomething after that initial page load

like image 859
hidar Avatar asked Jan 28 '26 06:01

hidar


1 Answers

You can define a boolean data item hasLoaded to be tested in the watch, and set it when the fetch has completed, or you can use this.$watch when your fetch has completed, rather than setting up a watch entry in your component.

It would look something like

this.$watch('list.items', (n, o) => {
  this.doSomething();
});
like image 144
Roy J Avatar answered Jan 31 '26 00:01

Roy J