vuex

 

 

 

 

modules

分模块管理

 

 

 

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './autoImport'
console.log('modules', modules)
Vue.use(Vuex)

export default new Vuex.Store({
  modules,

  // 各个模块公共的状态管理 (可以没有)
  state: {
    isLogin: false
  },
  mutations: {
    changeLogin (state, payload) {
      state.isLogin = payload.flag
    }
  }
})

  

/**
 * Person.js 个人中心公共给数据状态管理文件
 */
export default {
  namespaced: true,
  state: () => {
    return {
      name: 'zs',
      baseInfo: {
        sex: 'male',
        age: 10,
        email: '111@163.com'
      }
    }
  },
  getters: {
    showInfo (state) {
      return `${state.name}---${state.baseInfo.sex}`
    }
  },
  mutations: {
    changeAge (state, payload) {
      state.baseInfo.age = payload.age
    }
  },
   actions: {
    asyncChangeAge (context, payload) {
      // context.state 当前模块的state
      // context.rootState 整个store里面的全部状态
      setTimeout(() => {
        context.commit('changeAge', payload) //不要想当然的加Person/changeAge
      }, 2000)
    }
  }

}

 

使用

 <div class="home">
    <!--  访问state 平常是$store.state.XXX 现在需要加命名空间 $store.state.命名空间.XXX -->
    <div>直接访问person公共状态的state里面数据{{$store.state.Person.name}}</div>

   <!-- 访问getters 平常是$store.getters.XXX 现在是$store.getters['命名空间/XXX']-->
    <div>直接访问perosn公共状态的getters数据 {{$store.getters['Person/showInfo']}}</div>
    <el-button type="primary" @click="changeAge">changeAge</el-button>
          <el-button type="primary" @click="asyncChangeAge">asyncchangeAge</el-button>
    <div>person_age=={{$store.state.Person.baseInfo.age}}</div>

   
  </div>


methods: {

    changeAge () {
      // mutations 平常是this.$store.commit('XXX',payload) 现在是this.$store.commit('命名空间/XXX',payload)
      this.$store.commit('Person/changeAge', { age: 30 })
    },
 asyncChangeAge () {
      this.$store.dispatch('Person/asyncChangeAge', { age: 50 })
    }
  },

 

使用辅助函数

 

 

更好的vuex代码组织方式(前面可以不用看了 但是前面也可以用)

 

 modules/index.js实现自动化导入定义的modules

// 实现自动化导入。
const context = require.context('./', true, /\.js$/)
// console.log(context);
// console.log(context.keys()); //["./index.js", "./loading/index.js", "./tabBar/index.js"]
const res = {}
const arr = ['./index.js']
context.keys().forEach(filePath => {
  if (arr.includes(filePath)) return
  const key = filePath.match(/\/(.*)\./)[1]
  const value = context(filePath).default
  res[key] = value
})
export default res

  

store/index.js主入口文件

import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
console.log('modules', modules)
Vue.use(Vuex)

export default new Vuex.Store({
  modules,

  // 各个模块公共的状态管理 (可以没有)
  state: {
    isLogin: false
  },
  mutations: {
    changeLogin (state, payload) {
      state.isLogin = payload.flag
    }
  }
})

  

 

 

 

posted on 2020-12-22 12:26  章画  阅读(84)  评论(0编辑  收藏  举报

导航