Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 780
Pok3r Princ3 Avatar asked Sep 16 '25 15:09

Pok3r Princ3


2 Answers

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

like image 76
Igor Avatar answered Sep 18 '25 09:09

Igor


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.

like image 41
Evis Cheng Avatar answered Sep 18 '25 10:09

Evis Cheng