vuex-Vue.js 的中心化狀態(tài)管理方案
主要包含State, Getter, Mutations惊畏,Actions, Module槽唾。
State
存儲(chǔ)狀態(tài)數(shù)據(jù)紊浩,可以直接設(shè)置和獲取狀態(tài)值智亮。
結(jié)構(gòu)
state: {
token: "xxxx"
},
使用
設(shè)置值
this.$store.state.token = "xxxx"
獲取值
let token = this.$store.state.token
注意事項(xiàng)
data() {
return {
token:this.$store.state.token,
}
}
//如果這樣寫值更新不了
//這里需要把store 動(dòng)態(tài)的數(shù)據(jù)放到computed里面才會(huì)同步更新 視圖
computed:{
兩種方法
1.
getToken(){
return this.$store.state.token
}
2.
mapState{["token"]}
},
Getter
用于獲取需要處理的狀態(tài),例如:等級(jí)值為1继谚,返回初級(jí)戰(zhàn)士。
結(jié)構(gòu)
state: {
level: 1
},
getters: {
level: state => {
let level = ""
swicth(state.level){
case 1:
level = "初級(jí)戰(zhàn)士"
break;
case 2:
level = "中級(jí)戰(zhàn)士"
break;
case 3:
level = "高級(jí)戰(zhàn)士"
break;
}
return: level
}
}
使用
1.
this.$store.getters.level
2.
...mapGetters([
'level',
// ...
])
Mutations
需要對(duì)多個(gè)狀態(tài)值進(jìn)行修改阵幸,并且觸發(fā)頁面刷新花履。
結(jié)構(gòu)
mutations: {
SET_TOKEN: (state, userData) => {
state.token = userData.token
state.level = userData.level
},
LOGIN:(state,userData) => {
...
},
LOGOUT:(state,userData) => {
...
},
},
使用
this.$store.commit('SET_TOKEN',userData)
Actions
處理異步操作,例如:接口請求
結(jié)構(gòu)
actions: {
// 登錄
Login({commit}, userInfo) {
return new Promise((resolve, reject) => {
login(userInfo.user, userInfo.password).then(res => {
if(res.code==200){
console.log("登錄成功")
commit('SET_TOKEN', res.data )
resolve();
}else{
reject(res.message)
}
}).catch(error => {
console.log("登錄失敗")
reject(error)
})
})
},
}
使用
1.
this.$store.dispatch('Login',userInfo).then(() => {
···登錄處理
})
2.
methods:{
...mapActions([
'Login'
]),
changeLogin(){
this["Login"](userInfo)
},
}
Module
由于使用單一狀態(tài)樹挚赊,應(yīng)用的所有狀態(tài)會(huì)集中到一個(gè)比較大的對(duì)象诡壁。當(dāng)應(yīng)用變得非常復(fù)雜時(shí),store 對(duì)象就有可能變得相當(dāng)臃腫荠割。
結(jié)構(gòu)
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
export default store
store.state.a // -> moduleA 的狀態(tài)
store.state.b // -> moduleB 的狀態(tài)
使用
computed: {
...mapState('a', {
state: state => state
})
},
methods: {
// test1 模塊路徑名
...mapActions('a', [
'...'
]),
changeLogin(){
this["..."]('ok, a is login !!')
},
}
更詳細(xì)的用法還在摸索中妹卿,有問題歡迎指出~