admin管理员组

文章数量:1326516

I have a puted 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 puted property not to populate it again).How can i do that? I'm using a puted 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 puted property that populates the empty available machines array.

I have a puted 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 puted property not to populate it again).How can i do that? I'm using a puted 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 puted property that populates the empty available machines array.

Share Improve this question asked Aug 22, 2019 at 9:22 Pok3r Princ3Pok3r Princ3 1473 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

It' not remended to make puted 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).

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.

本文标签: javascriptHow to run a vue computed property only onceStack Overflow