[ vue ] 解耦vuex(按照组件来组织vuex的结构)

问题描述

随着应用复杂度的增加,vuex用一个 store/index.js 文件来描述已经很难维护了,我们想把这些状态分割到单独文件里面。

参考1:https://vuex.vuejs.org/zh/guide/structure.html

参考2:https://github.com/PanJiaChen/vue-element-admin

[ 最终项目结构 ]

E:.
│          
├─components
│     article.vue
│     header.vue
│     sidebar.vue
│     ...
│      
├─router
│      index.js
│      
├─store
   │  index.js
   │  
   └─ modules
           article.js
           header.js
           sidebar.js

解决方案

1. article.js / header.js / sidebar.js

注意开启了namespaced,在取的state的时候要这样写: this.$store.state.article.msg 

const state = {
    msg:''
}
const mutations = {
    CHANGE_MSG:(state,val)=>{
        state.msg = val
    }
}
const actions = {
    change_msg(context,val){
        context.commit('CHANGE_msg',val)
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}

2. index.js

  1. 注意mymodules的构成

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const mymodules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^./(.*).w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

/**
mymodules:{
  article:{
    namespaced:true,
    state:{},
    ...
  },
  header:{
    namespaced:true,
    state:{},
    ...
  }
}
 */
console.log(mymodules)
const store =  new Vuex.Store({
    modules:mymodules
})

export default store
原文地址:https://www.cnblogs.com/remly/p/12674090.html