Say I have a component that is loaded with data from an initial API call inside mounted().
Any further changes to a state variable will not be reflected in the component since the first API call is inside mounted.
Can we use watcher to deal with this?
For Example,
data() { return { someVariableInStore: this.$store.state.test, variableThatUpdatesTheComponent: "" }, watch: { someVariableInStore(){ // Based on someVariableInStore run a function that updates variableThatUpdatesTheComponent someFunction(); } }
Is there a better way of doing this if not the above solution ?
Advertisement
Answer
The correct approach in this case is to use a computed property. Instead of manually calling the update function, let Vue call it for you:
computed: { variableThatUpdatesTheComponent() { // The logic of `someFunction()` can go here return this.$store.state.test + "foo"; } }