user2410266
user2410266

Reputation: 551

Using Created and Watcher in VUE.JS

I am using watch and created method for the same data.Is it duplicate code? Is there a better way to do it?

props: {  
 regionList: {
   type: Array,
  },
},

data() {
  return {
    regions: [],
  };
},

watch: {
  regionList() {
    if (this.regionList) {
      this.regions = this.regionList;
    }
  },
},
created() {
  if (!this.regionList) {
   this.getApi();
  } else {
   this.regions = this.regionList;
 }
},

Upvotes: 0

Views: 46

Answers (1)

Estus Flask
Estus Flask

Reputation: 222603

It is what immediate watcher is for:

watch: {
  regionList: {
    immediate: true,
    handler(newVal) {
      if (newVal.length) {
        this.regions = newVal;
      }
    }
  },
},
created() {
  if (!this.regionList) {
   this.getApi();
  }
},

Upvotes: 1

Related Questions