问题描述

随着应用复杂度的增加,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

最新文章

  1. django学习记录--第一个网页“hello django”
  2. Google Code Jam 2009 Qualification Round Problem C. Welcome to Code Jam
  3. 【GK101 谐波数据生成器】上位机软件升级(版本:1.1)
  4. 线段树---HDU1394Minimum Inversion Number
  5. 你该学点HTML/CSS知识的9大理由
  6. list集合接口
  7. ItemsPanelTemplate的用法
  8. BootStrap的入门和响应式的使用
  9. 彻底理解线程同步与同步代码块synchronized
  10. GIT入门笔记(12)- 删除文件、提交删除和恢复删除
  11. Storage 001 电商数据库设计
  12. 黄聪:VS2017调试时提示“运行时无法计算表达式的值”
  13. kafka-java客户端连接
  14. POJ-1959 Darts
  15. jackson 常用注解,比如忽略某些属性,驼峰和下划线互转
  16. Oracle EBS 创建资产报错
  17. Java并发编程原理与实战三:多线程与多进程的联系以及上下文切换所导致资源浪费问题
  18. sicily 1012. Stacking Cylinders & 1206. Stacking Cylinders
  19. Ubuntu切换root用户权限
  20. 【Linux】通过传入变量进行数学运算

热门文章

  1. 使用buffered流结合byte数组,读入文件中的内容,包括中文字符
  2. 3.Vue.js-目录结构
  3. ASP.NET Core中使用漏桶算法限流
  4. minikube metrics-server HPA 自动扩缩容错误
  5. DevOps的分与合
  6. 两大js移动端调试神器 / 调试工具分享 !
  7. WPF之交互触发器(CallMethodAction)学习
  8. AT5341 [ABC156D] Bouquet 题解
  9. c++设计模式概述之状态
  10. soundcloud to mp3