torbilote
torbilote

Reputation: 141

Start watcher after created() is done

My goal is to initially set up a data property when component is created and then set up a watcher on this property. The issue I am struggling with is the watcher catches initial property change in created method but this is not what I want. I would rather to watch data property only after initial change is made in created().

export default {
 name: 'testComponent',

 data() {
  return {
   testValue: 1;
  }
 },

 watch: {
  testValue() {
   console.log('watcher catches!');
  },

 created() {
   console.log(this.testValue);
   this.testValue = 2;
   console.log(this.testValue);
 }
}

// CONSOLE OUTPUT:  1 -> watcher catches! -> 2

Can you tell me how to achieve behaviour like that?

Upvotes: 3

Views: 1437

Answers (1)

slauth
slauth

Reputation: 3178

No idea why you'd want that but you could simply do it like this:

export default {
 name: 'testComponent',

 data() {
  return {
   ready: false,
   testValue: 1
  }
 },

 watch: {
  testValue() {
   if (!this.ready) return;
   console.log('watcher catches!');
  },

 created() {
   this.testValue = 2;
   this.ready = true;
 }
}

Upvotes: 3

Related Questions