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?
Nope, if you need to do something asynchronous, then you can't use a computed property.
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.
For passing the parameters to the computed property, we just pass the parameters as we do for the function.
Computed properties are by default getter-only, but you can also provide a setter when you need it: // ... Now when you run vm.
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
}
}
There are 2 approaches here:
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;
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With