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