在简单的 VueJS 测试中混淆了 Vuex commit/dispatch
Confused with Vuex commit/dispatch in simple VueJS test
摘自本书:
To invoke a mutation handler, you need to call store.commit with its type: store.commit('increment')
突变必须始终同步。
摘自本书:
动作提交突变(可以是异步的)
Actions are triggered with the store.dispatch method: store.dispatch('increment')
所以大部分时间是 action
-> mutation
-> new state
。
所以让我感到困惑的是一个非常简单的例子,我试图显示一个对象的异步结果 getTest
为什么 Vue 看不到我 不是在调用一个 mutation,而是在组件加载时调用一个 action?
你在说什么"book"?我问是因为你混合使用了新的 Vuex 2.*
和旧的 Vuex 1.*
语法,这在 2.*
中不再有效,所以我假设你部分地从过时的资源。
(旁注:您为什么使用 Vue 1?Vue2.*
已经发布 10 多个月了...)
- 你的 action 和 mutation 定义是正确的,但是 Vuex 中的组件中不再有
vuex: {}
key 2.*
- 此外,您正在尝试调度一个动作 'INCREMENT',但是您的商店只有那个名称的突变,没有动作。所以你必须使用
commit
而不是 dispatch
.
相反,您直接将计算的道具和方法添加到您的实例中,或者使用 Vuex 提供的 map*
帮助程序:
var vm = new Vue({
el: '[vue=app]',
data: {
welcome: 'Testing Vuex'
},
store: myStore,
created() {
this.$store.dispatch(FETCH_TEST_STATE)
},
computed: {
...Vuex.mapState( {
count: state => state.count,
getTest: state => state.testState
}),
}
methods: {
increment({dispatch}) {
this.$store.commit('INCREMENT', 1)
}
}
})
- 您从
created
调用的操作无效,因为 async/await 在 codepen 上运行
- 从此操作调用的提交未设置任何状态。
解决所有这些问题,这是您的工作示例:
摘自本书:
To invoke a mutation handler, you need to call store.commit with its type:
store.commit('increment')
突变必须始终同步。
摘自本书:
动作提交突变(可以是异步的)
Actions are triggered with the store.dispatch method:
store.dispatch('increment')
所以大部分时间是 action
-> mutation
-> new state
。
所以让我感到困惑的是一个非常简单的例子,我试图显示一个对象的异步结果 getTest
为什么 Vue 看不到我 不是在调用一个 mutation,而是在组件加载时调用一个 action?
你在说什么"book"?我问是因为你混合使用了新的 Vuex 2.*
和旧的 Vuex 1.*
语法,这在 2.*
中不再有效,所以我假设你部分地从过时的资源。
(旁注:您为什么使用 Vue 1?Vue2.*
已经发布 10 多个月了...)
- 你的 action 和 mutation 定义是正确的,但是 Vuex 中的组件中不再有
vuex: {}
key2.*
- 此外,您正在尝试调度一个动作 'INCREMENT',但是您的商店只有那个名称的突变,没有动作。所以你必须使用
commit
而不是dispatch
.
相反,您直接将计算的道具和方法添加到您的实例中,或者使用 Vuex 提供的 map*
帮助程序:
var vm = new Vue({
el: '[vue=app]',
data: {
welcome: 'Testing Vuex'
},
store: myStore,
created() {
this.$store.dispatch(FETCH_TEST_STATE)
},
computed: {
...Vuex.mapState( {
count: state => state.count,
getTest: state => state.testState
}),
}
methods: {
increment({dispatch}) {
this.$store.commit('INCREMENT', 1)
}
}
})
- 您从
created
调用的操作无效,因为 async/await 在 codepen 上运行
- 从此操作调用的提交未设置任何状态。
解决所有这些问题,这是您的工作示例: