Pok3r Princ3
Pok3r Princ3

Reputation: 147

How to run a vue computed property only once?

I have a computed property that populates an array, however i'm working with this array afterwards (pushing from & to it) and i want once the array is empty, to remain empty (said computed property not to populate it again).How can i do that? I'm using a computed property because i'm fetching data from the Vuex store via getter. Here's the property in question:

populateAvailableMachines() {
  Object.values(this.userData).forEach(user => {
    if (this.$auth.user().id == user.id) {
      if (this.availableMachines.length == 0) {
        Object.keys(user.machine).forEach(key => {
          this.availableMachines.push(user.machine[key].machine_name);
        });
      }
    }
  });
},

And here's the method that pushes/splices:

addMachineTab(item) {
  let index = this.availableMachines.indexOf(item);
  this.selectedMachines.push(this.availableMachines.splice(index, 1));
},

What i want to achieve is, once all the values from the available machines array are moved to the selected machines array, not to re-run the computed property that populates the empty available machines array.

Upvotes: 4

Views: 6548

Answers (2)

Evis Cheng
Evis Cheng

Reputation: 91

Use watcher instead.

watch: {
  userData: {
    handler: function (val, oldVal) {
      if(this.availableMachines.length > 0){
        // put your populate logic here
      }
    },
    deep: true
  }
},

Besides, you may need to initialize your data(userData and availableMachines) in created or mounted hook.

Upvotes: 3

Igor
Igor

Reputation: 809

It' not recommended to make computed properties produce any side effects like data mutating. It would better to move populateAvailableMachines function to methods and call it only once (e.g. on mounted).

Upvotes: 5

Related Questions