vuex 模块化使用

139 阅读1分钟

文件目录

image.png

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import logic from './modules/logic'
Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    logic,
  },
  state: {

  },
  mutations: {

  },
  actions: {

  },
  getters
})

logic.js

const logic = {
  state: {
    changeBool: false,
    changeStr: "",
    changeArr: [],
    changeObj: {},
  },
  mutations: {
    toggleChangeBool (state, val) {
      state.changeBool = val
    },
    toggleChangeStr (state, val) {
      state.changeStr = val
    },
    toggleChangeArr (state, val) {
      state.changeArr.push(val);
    },
    toggleChangeObj (state, val) {
      state.changeObj[val.id] = val.val;
    },
  },
  actions: {
    handleChangeBool ({ commit }, val) {
      commit("toggleChangeBool", val);
    },
    handleChangeStr ({ commit }, val) {
      commit("toggleChangeStr", val);
    },
    handleChangeArr ({ commit }, val) {
      commit("toggleChangeArr", val);
    },
    handleChangeObj ({ commit }, val) {
      commit("toggleChangeObj", val);
    }
  }
}
export default logic

main.js

import store from './store'
new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

使用

that.$store.dispatch('handleChangeBool', false)

computed: {
    pageBool: {
      get: function () {
        return this.$store.state.logic.changeBool;
      },
      set: function (val) {
        this.$store.state.logic.changeBool = val;
      }
    },
}