VUEX封装module

VUEX封装module

目录结构

VUEX封装module_第1张图片

store/index.js,配置,以及导入两种方式

import Vue from 'vue'
import Vuex from 'vuex'
import m from './module/m'
import authority from './module/authority'
// 调试方法
import createLogger from 'vuex/dist/logger'

// 判断环境
const debug = process.env.NODE_ENV !== 'production'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    m: m,
    authority: authority
  },
  strict: debug,
  plugins: debug ? [createLogger()] : []
})

// store.state.hw // -> hw 的状态
// store.state.m // -> hw 的状态

authority/index.js ,官方版本

export default {
  // 是否对应 模块名 响应数据
  namespaced: true,
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 5
    },
    // 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  },

  actions: {
    // 同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}

m/index.js,封装版本

import * as actions from './actions'
import * as getters from './getters'
import state from './state'
import mutations from './mutations'

export default {
  // 是否对应 模块名 响应数据
  namespaced: true,
  actions,
  getters,
  state,
  mutations
}

m/action.js

import * as types from './mutation-types'

export const incrementIfOddOnRootSum = ({ state, commit, rootState }) => {
  if ((state.count + rootState.count) % 2 === 1) {
    commit([types.SET_INCREMENT])
  }
}

m/getters.js

export const doubleCountm = (state) => {
  return state.count * 2
}

m/mutation-types.js

export const SET_INCREMENT = 'increment'

m/mutations.js

import * as types from './mutation-types'

const mutations = {
  [types.SET_INCREMENT] (state) {
    // 这里的 `state` 对象是模块的局部状态
    state.count++
  }
}

export default mutations

 m/state.js

const state = {
  count: 10
}

export default state

使用:Home.vue




 

 

 

 

 

你可能感兴趣的:(vue)