【问题标题】:Setting values with Vuex使用 Vuex 设置值
【发布时间】:2020-09-17 10:28:39
【问题描述】:

我目前正在尝试学习 Vuex。

我希望每次使用突变(changeNumber).

let state = {
  counter: 0,
  someOtherValue: 'Text'
}

let changeNumber = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  changeNumber,
  state
})

Vue.component('counter-button', {
  computed: {
    counter() {
      return this.$store.state.counter
    }
  },
  template: `<input :value="$store.state.counter" @click="$store.commit('increment')" type="button">`
})

Vue.component('some-component', {
  computed: {
    someOtherValue() {
      return this.$store.state.someOtherValue
    }
  },
  template: '<div>{{ someOtherValue }}</div>'
})

new Vue({
  el: '#app',
  store,
  template: '<some-component></some-component>',

})

我的代码被机器人更正了,我收到了两个错误。我的代码有什么问题?

Err) clicking on the paragraph causes the number value to change
Err) triggering the changeNumber mutation causes the number value to change

【问题讨论】:

  • 到目前为止你尝试过什么?我认为您应该研究 Vuex.Store() 的论点。
  • 我已尝试将代码重新格式化为我认为已更正的内容,但这是我所取得的最远距离。能详细点吗?

标签: javascript html vue.js vuex


【解决方案1】:

您应该将突变传递到键 mutations 而不是 changeNumber 下的存储。请注意,在您的代码中,changeNumber 不是突变,increment 是实际的突变。

let mutations = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  mutations,
  state
})

【讨论】:

  • 我添加了这些更改,但我仍然得到与以前相同的输出...
猜你喜欢
  • 2019-04-24
  • 2019-04-16
  • 2019-08-02
  • 2019-01-24
  • 2020-01-30
  • 1970-01-01
  • 2019-05-29
  • 2019-10-12
  • 2020-11-24
相关资源
最近更新 更多