Search code examples
javascriptvue.jsvuex

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.


Solution

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