1.State定義:State提供唯一的公共源粒褒,所有共享的數(shù)據(jù)都要統(tǒng)一放 到Store的State中進(jìn)行存儲(chǔ)
2.Mutation定義:用于變更Store的數(shù)據(jù)
3.Action定義:用于處理異步任務(wù)
4.Getter定義:用于對(duì)Store中數(shù)據(jù)進(jìn)行加工處理成新的數(shù)據(jù)
State的用法
//創(chuàng)建store 的數(shù)據(jù)源,提供唯一公共數(shù)據(jù)
const store =new Vuex.Store({
State:{ count: 0 }
})
組件訪問State中數(shù)據(jù)的第一種方式:
this.$store.state.全局?jǐn)?shù)據(jù)名稱
在state中添加count數(shù)據(jù)
在這里插入圖片描述
在組件中直接使用數(shù)據(jù)
在這里插入圖片描述
組件訪問State中的第二種方法
在這里插入圖片描述
在這里插入圖片描述
Mutation的用法
const store = new Vuex.Store({
state:{
count: 0
},
mutations:{
add(state){
state.count++
}
}
})
在組件中用commit方法直接調(diào)用
methods:{
handlel(){
this.$store.commit("add)
}
}
Action用法(用于處理異步操作)
const store = new Vuex.Store({
state:{
count: 0
},
mutations:{
add(state){
state.count++
}
actions:{
//用commit調(diào)用mutations里的方法
addAsync(context){
setTimeout(()=>{
context.commit("add)
}诚镰,1000)
}
}
})
在組件里觸發(fā)
methods:{
handel(){
//觸發(fā)actions
this.$store.dispatch("addAsync)
}
}
Getter的使用
const store - new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state=>{
return '當(dāng)前的最新數(shù)據(jù)是【'+ state.count+'】'
}
}
})
在組件中觸發(fā)
方法1
[圖片上傳失敗...(image-f5c8ab-1598980188291)]
方法2
在這里插入圖片描述
相關(guān)內(nèi)容請(qǐng)瀏覽《普歌-智音團(tuán)隊(duì) javascript-DOM重點(diǎn)總結(jié)》
作者:lihaijin8090
本文源自:lihaijin8090的《普歌-智音團(tuán)隊(duì) vuex里State奕坟,Mutation,Action清笨,Getter的使用》
本文版權(quán)歸作者和CSDN共有月杉,歡迎轉(zhuǎn)載,且在文章頁面明顯位置給出原文鏈接抠艾,未經(jīng)作者同意必須保留此段聲明苛萎,否則保留追究法律責(zé)任的權(quán)利。