這里主要是關(guān)于Vuex中action的介紹
一、action
1.產(chǎn)生原因
??當(dāng)在mutations中進(jìn)行異步操作時(shí),Devtool不能夠?qū)崟r(shí)跟蹤失球,導(dǎo)致最終在Devtool中記錄的是錯(cuò)誤的信息。比如:
const store = new Vuex.Store({
state:{
info:{
name:'haha',
age:13,
height:1.45
}
},
mutations:{
changeInfo(state){
// 異步操作
setTimeout(()=>{
state.info.name='哈哈'
},1000)
}
}
})
上述代碼主要是同異步操作來將“haha”修改成“哈哈”。結(jié)果如圖所示:
??當(dāng)在mutations使用異步操作時(shí)榕酒,雖然頁面中的數(shù)據(jù)修改了,但是在Vuex總state記錄的仍舊是以前的數(shù)據(jù)故俐。
??其實(shí)數(shù)據(jù)是修改成功了想鹰,但是mutations中的Devtool在跟蹤時(shí)沒有記錄,就導(dǎo)致記錄的的錯(cuò)誤的信息药版。
??所以不能再mutations中進(jìn)行一步操作辑舷,這時(shí)我們就需要action幫我們進(jìn)行一步操作。
2.定義
Action類似于Mutation, 但是是用來代替Mutation進(jìn)行異步操作的槽片。
3.使用方式
使用方式和mutations類似何缓,但是有兩點(diǎn)不同:
① 參數(shù):傳入的參數(shù)是context。該參數(shù)相當(dāng)于store對(duì)象
② 調(diào)用方式:使用dispatch調(diào)用还栓,而不是使用commit
具體見下面的代碼:
const store = new Vuex.Store({
mutations:{
state.info.name='哈哈'
},
actions:{
achangeInfo(context){
setTimeout(()=>{
context.commit('changeInfo')
},1000)
}
},
})
<script>
import store from '../store/index.js'
export default {
name: 'App',
methods:{
changeInfo(){
this.$store.dispatch('achangeInfo')
}
}
}
</script>
可以發(fā)現(xiàn)mutations中的Devtool記錄的數(shù)據(jù)也跟著發(fā)生了改變碌廓。
4.傳遞參數(shù)
傳遞參數(shù)的方式和mutations類似,下面進(jìn)行簡(jiǎn)單的傳遞字符串參數(shù)剩盒,具體代碼如下:
const store = new Vuex.Store({
mutations:{
state.info.name='哈哈'
},
actions:{
achangeInfo(context,payload){
setTimeout(()=>{
context.commit('changeInfo')
console.log(payload)
},1000)
}
},
})
<script>
import store from '../store/index.js'
export default {
name: 'App',
methods:{
changeInfo(){
this.$store.dispatch('achangeInfo','我是payload')
}
}
}
</script>
發(fā)現(xiàn)傳遞參數(shù)也是可以的谷婆,并且成功在控制臺(tái)中顯示了。
5.action內(nèi)部使用Promise
??當(dāng)數(shù)據(jù)commit之后就意味著修改成功了,此時(shí)想要告訴外界波材,數(shù)據(jù)已經(jīng)修改成功了并且除了修改數(shù)據(jù)之外我們還可以做別的操作股淡。該需求可以用Promise實(shí)現(xiàn),具體先看下面代碼:
actions:{
achangeInfo(context,payload){
return new Promise((resolve,reject) =>{
setTimeout(()=>{
context.commit('changeInfo')
console.log(payload)
resolve('1111')
},1000)
})
}
}
<script>
changeInfo(){
this.$store
.dispatch('achangeInfo','我是payload')
.then(res =>{
console.log(res)
})
}
</script>
??上述代碼的主要作用是當(dāng)數(shù)據(jù)修改成功之后廷区,就在控制臺(tái)上打印“1111”唯灵。具體思路是當(dāng)action運(yùn)行到commit方法時(shí),就會(huì)執(zhí)行changeInfo函數(shù)隙轻,然后在回調(diào)changeInfo函數(shù)埠帕。
??本案例中,當(dāng)執(zhí)行achangeInfo函數(shù)時(shí)玖绿,就返回 Promise敛瓷,而achangeInfo是通過dispatch調(diào)用的,其上述的代碼可以等價(jià)為下面的代碼:
<script>
changeInfo(){
//this.$store
//.dispatch('achangeInfo','我是payload')
new Promise((resolve,reject) =>{
setTimeout(()=>{
context.commit('changeInfo')
console.log(payload)
resolve('1111')
},1000)
.then(res =>{
console.log(res)
})
}
</script>
??以上就是action相關(guān)的知識(shí)斑匪,總結(jié)起來就是兩點(diǎn):處理異步操作和在內(nèi)部使用Promise呐籽。