Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - Is it okay to use watch to keep track of store changes after initial mount?

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 ?

question from:https://stackoverflow.com/questions/65889372/is-it-okay-to-use-watch-to-keep-track-of-store-changes-after-initial-mount

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...