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
315 views
in Technique[技术] by (71.8m points)

vue.js - Vue + Vuex: variable stored in component saves changes even after leaving and coming back

I am assigning a variable in my component to a variable stored in vuex (let's say it's empty at the beginning) like

export default {
  name: "Step1",
  [...]
  data() {
    return {
      participants: this.$store.state.participants,
  [...]

later I work with this variable and add something like

  [...]
  methods: {
    add: function() {
      this.participants.push("foo");
    },
    [...]

I never update the variable in the store as I double-check on devtools. I expect this behaviour and expect the variable to be empty again after moving to another route and coming back. But somehow the variable in the component still contains "foo" despite the variable in the store is empty.

I'd appreciate a hint what I don't understand in Vue, it's driving me crazy.


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

1 Reply

0 votes
by (71.8m points)

You should never change the store state directly like that. As stated in the docs:

The only way to actually change state in a Vuex store is by committing a mutation.

So in your store, you have to add a mutation method, like so:

mutations: {
    addParticipant(state, participant) {
      state.participants.push(participant);
    }
}

And call that: this.$store.commit('addParticipant', 'Foo')


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

...