// Vuex store 示例代码,包含 dispatch 的使用
// 定义 Vuex store
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
// 定义一个 action,通过 dispatch 触发
incrementAsync ({ commit }) {
return new Promise((resolve) => {
setTimeout(() => {
commit('increment')
resolve()
}, 1000)
})
}
}
})
// 在组件或其他地方使用 dispatch 来触发 action
store.dispatch('incrementAsync').then(() => {
console.log('异步操作完成,count 现在是:', store.state.count)
})
// 解释说明:
// 1. `actions` 中定义了名为 `incrementAsync` 的异步操作。
// 2. `dispatch` 方法用于触发 action,这里我们触发了 `incrementAsync`。
// 3. `incrementAsync` 内部使用 `commit` 触发 mutation,从而修改 state。
// 4. `dispatch` 返回一个 Promise,因此我们可以使用 `.then()` 来处理异步操作完成后的逻辑。
上一篇:vue.config
下一篇:vue3 自定义组件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站