Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to execute function once computed property updates

Currently I have a component that has a computed property that updates from the Vuex store. This part works perfectly. What I'm confused about is once that computed property updates, I have to always tweak the data accordingly for my view. WHat is the best way to achieve this?

For example:

My component has:

    computed: {
        players: function() {
            return this.$store.state.players;
        },

I previously had a function setupPlayers(data) that tweaked this info and provided it for the view.

My question now is if computed players changes I'd like to run a function that tweaks the data for the view. How do I do this? OR is my approach incorrect?

like image 480
KingKongFrog Avatar asked Sep 18 '17 14:09

KingKongFrog


People also ask

Can a computed property be async?

Nope, if you need to do something asynchronous, then you can't use a computed property.

Are computed properties reactive?

Once we've created our computed prop, we can access it like we would any other prop. This is because computed props are reactive properties, along with regular props and data.

Can we pass parameters to computed property?

For passing the parameters to the computed property, we just pass the parameters as we do for the function.

Can we use setters and getters in computed properties?

Computed properties are by default getter-only, but you can also provide a setter when you need it: // ... Now when you run vm.


2 Answers

You should make data you are updating a computed property and have it dependant on the players computed property:

computed: {
  players: function() {
    return this.$store.state.players;
  },
  myData: function() { // will update automatically whenever this.players changes
    var players = this.players;
    // do something players data
  }
}

If you're unable to make that data a computed property for any reason, then you could also just use a watcher:

watch: {
  players: function(value) {
    // update your data
  }
}
like image 89
thanksd Avatar answered Oct 22 '22 02:10

thanksd


There are 2 approaches here:

  1. Don't access the data directly from the state, but rather via a getter, and then the getter can manipulate the data before returning it.
  2. You can run any logic in the computed property before returning it, as long as you are not performing async or heavy operations, so you can just manipulate the players array in the computed:

    computed: {
        players: function() {
            var players = this.$store.state.players;
            //do something here
            ....
            return players;
        },
    
like image 36
Tomer Avatar answered Oct 22 '22 02:10

Tomer