Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to trigger the processing of new values added to a vuex store?

I have a vuex store that stores entries:

const store = createStore({
  state() {
    return {
      entries: [
        {
          id: 1,
          date-of-birth: "2020-10-15T14:48:00.000Z",
          name: "Tom",
        },
      ],
    };
  },
});

I get these entries by using a getter in a computed property:

computed: {
  entries() {
    var entries = this.$store.getters.entries;
  }
}

For some reason, I want to always output the newest date-of-birth in the store. Initially, I was able to do this in two ways:

  • By creating an additional computed property newest_date-of-birth
  • By simply adding a new data variable newest_date-of-birth that gets set within (e.g.) the beforeMounted hook.

However, when I add a new entry (through the app), both these methods do not update newest_date-of-birth as only the computed property entries is triggered.

I tried to solve this in two approaches:

  • When I try to update newest_date-of-birth within the computed property entries, I get advised not to do this as it seems to be bad practise (no-side-effects-in-computed-properties).
  • Also watching over computed property entries does not work; apparently this only works for data variables.

So my question is: How do I update newest_date-of-birth after a value is added to (or removed from, for that matter) the store?

Thanks!

question from:https://stackoverflow.com/questions/66054179/how-to-trigger-the-processing-of-new-values-added-to-a-vuex-store

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

1 Reply

0 votes
by (71.8m points)

You are only showing the state property of your vuex object. I assume you are also using the mutation property to set internal values.

If so, all you have to do is set multiple states on a single mutation and both of them will update in your computed values, like this:

const store = new Vuex.Store({
  state: {
    entries: []
    lastEntrie: null
  },
  mutations: {
    addEntrie (state, entrie) {
      state.entries.push(entrie);
      state.lastEntrie = entrie;
    }
  }
})

Then, in your computed values:

computed: {
  myEntries () {
    return this.$store.state.entries
  }
  theLastEntrie () {
    return this.$store.state.lastEntrie
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...