// 使用輔助函數前必須導入
import { mapState , mapGetters, mapMutations, mapActions } from 'vuex';
(1) vuex 中 state 定義的數據
state: {
msg: 'vuex中的數據'
}
使用方法: 在組件(computed)中使用
1. msg() {
return this.$store.state.msg;
},
2. ...mapState(['msg'])
(2) vuex 中 getters 定義的數據
getters() {
score30(state) {
// p(state, getters, rootState, rootGetters)
//state: 當前模塊的state
//getters: 當前模塊的getters
//rootState: 全局的state
//rootGetters: 全局的getters
let ps = state.price.filter(v => {
return v >= 30;
})
return ps.join('-');
}
}
使用方法: 在組件(computed)中使用
1. score30() {
return this.$store.getters.score30;
},
2. ...mapGetters(['score30'])
(3) vuex 中 mutations 定義的修改state的方法
mutations: {
changeMsg(state, data) {
//state: 當前模塊的state
//data: 組件提交mutation時攜帶的參數(載荷)
console.log('data ==> ', data);
state.msg = data.name;
},
},
使用方法: 在組件(methods)中使用
1. changeStateMsg() {
this.$store.commit('changeMsg', 'kevin');
},
2. ...mapMutations(['changeMsg']), // 調用時要傳參, 載荷(即要修改state的值為什么)
(4) vuex 中 actions 定義的提交mutations的方法
actions: {
ac3({commit}, data) {
//提交mutations的changeMsg
commit('changeMsg', data)
//actions內部可以返回一個結果讓組件使用
return context.state.msg;
}
}
使用方法: 在組件(methods)中使用
1.ac3() {
//提交actions並且攜帶一個參數后,返回一個promise, 就可以執行異步操作
this.$store.dispatch('ac3', '我要修改vuex中的數據').then(v => {
// v ==> context.state.msg ==> vuex中的數據 (actions內部返回的結果)
console.log('v ==> ', v);
});
2....mapActions(['ac3'])
以上。由本人學習過程中整理的,如有錯誤歡迎提出改正!!!