vuex的使用
1.組件中經過dispatch事件觸發actions
eg:
methods: {
事件名: function() {
this.$store.dispatch("鍵值名", 須要存儲的值);
},
}
2.經過actions進行commit提交給mutation
eg:action.js
鍵值名({commit},須要存儲的值){
commit(types.NEWSHOW,須要存儲的值);
},
3.mutation經過mutate給state
eg:mutation.js
[types.NEWSHOW](state,須要存儲的值){
state.須要存儲的值的名稱=須要存儲的值;
},
4.在store.js裏進行getter處理
eg:
show(state){
return state.須要存儲的值的名稱
},
5.在組件裏進行獲取
eg:
import { mapGetters } from "vuex";
computed: {
...mapGetters(["show"])
},
6.注意:使用常量替代 Mutation 事件類型
eg:mutation_type.js
export const NEWSHOW="NEWSHOW"
eg:目錄結構:
store
action.js
import * as types from './mutation_type'這是全局引入,也能夠按需引入
export default{
newShow({commit},bData){
commit(types.NEWSHOW,bData);
}
}
mutation.js
import * as types from './mutation_type'
export default{
[types.NEWSHOW](state,bData){
state.show=bData;
}
}
mutation_type.js
export const NEWSHOW="NEWSHOW"
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './action'
import mutations from './mutation'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
show: false,
},
actions,
mutations,
getters:{
show(state){
console.log(state.show)
return state.show
}
})
export default store
至於事件觸發和組件裏獲取和上面同樣的!