區(qū)別:
1.Action提交的是mutation,而不是直接變更狀態(tài)亡脑,可以包含任意的異步操作。
2.dispatch推送一個(gè)action邀跃。
說實(shí)話霉咨,官網(wǎng)看的感覺不是很懂。還是先說明這兩個(gè)函數(shù)調(diào)用的都是哪個(gè)里面的方法吧拍屑。
1.dispatch 異步操作 this.store.commit('mutations的方法', arg),調(diào)用mutations里的方法僵驰。
使用方法步驟:
const user = {
state: {
token: ''
},
mutations: {
SET_TOKEN: (state, token) => {
state.token ="test " +token
},
},
actions: {
// 登錄
Login({commit}, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo.account, userInfo.password).then(aa => {
if(aa.status==200){
const tokenSuccess = aa.data.token.tokenValue
commit('SET_TOKEN', tokenSuccess )
document.cookie=`cookie地址`;
token="test"+tokenSuccess ;
//setToken("test" +token)
resolve();
}
}).catch(error => {
console.log("登錄失敗")
reject(error)
})
})
},
}
}
toLogin() {
this.$store.dispatch('Login',arg).then(() => {
})
在上面代碼中喷斋,在mutations中使用箭頭函數(shù)更改state中的token數(shù)據(jù)。然后在actions中Login函數(shù)中通過commit('SET_TOKEN', tokenSuccess )來進(jìn)行調(diào)用此函數(shù)并傳參矢渊,才能在store存儲(chǔ)成功继准。在需要的組件中使用this.$store.dispatch('actions方法')來調(diào)取store里的對應(yīng)方法,從而更新矮男。