actions异步处理
**注意:
** commit 和dispatch的区别在于commit是提交mutatious的同步操作,dispatch是分发actions的异步操作dispatch:含有异步操作,例如向后台提交数据,写法: this. s t o r e . d i s p a t c h ( ‘ a c t i o n 方 法 名 ’ , 值 ) c o m m i t : 同 步 操 作 , 写 法 : t h i s . store.dispatch(‘action方法名’,值) commit:同步操作,写法:this. store.dispatch(‘action方法名’,值)commit:同步操作,写法:this.store.commit(‘mutations方法名’,值)
Home.vue
<template>
<div class="home">
<h2>使用全局的状态管理</h2>
<h3>Num:{
{$store.state.num}}</h3>
//Actions异步处理
<button @click="cnum">Action</button>
<h3>state中的平方{
{vuexpow}}</h3>
<h3>使用getter中的计算属性:{
{$store.getters.vxnumpow}}</h3>
<button @click="$store.state.num--">-</button>
<button @click="$store.state.num++">+</button>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
},
data() {
return {
count: 2
}
},
computed: {
vuexpow() {
return this.$store.state.num * this.$store.state.num
}
},
methods: {
cnum() {
//通过分发的方法,调用Action里定义的方法
this.$store.dispatch('demo')
}
}
}
</script>
index.js
import {
createStore } from 'vuex'
export default createStore({
state: {
//任何地方都可使用这个状态管理
num: 2,
},
getters: {
//第一个参数就是state
vxnumpow(state) {
return state.num * state.num;
},
},
mutations: {
cnum(state) {
state.num = 100
}
},
//actions处理异步处理
actions: {
demo(context) {
//context上下文 context也可用state、commit、getters替代
setTimeout(()=>{
// context.state.num = 100
//这个cnum是在mutations里的函数,通过提交用来修改状态
context.commit('cnum')
},3000)
},
//写法等价于
demo({
state,commit,getters}) {
setTimeout(()=>{
commit('cnum')
},3000)
},
modules: {
}
})
效果
点击按钮,大约3秒,num值从2变为100
Actions亦可传递参数
Home.vue
methods: {
cnum() {
//传递参数的方式
this.$store.dispatch('demo', {count:88, name:'vuex'})
}
}
index.js
actions: {
//写法等价于
demo({
state,commit,getters},payload) {
setTimeout(()=>{
……
console.log(payload);
},3000)
},
modules: {
}
})