以vuex分模块为例,记录一下require.context()在项目中的应用例子,做一个笔记,方便后续查阅
1. require.context ( directory , useSubdirectories , regExp )
- directory: 表示检索的目录 (路径)
- useSubdirectories:表示是否检索子文件夹 (Boolean值)
- regExp: 匹配文件的正则表达式,一般是文件名
返回值: 符合条件的文件列表
铺垫
// arr.keys()与Object.keys()的区别
var arr = ["a", "b", "c"];
var sparseKeys = Object.keys(arr); //==> [0, 1, 2]
var denseKeys = [...arr.keys()]; //==>['0',"1" ,'2']
2. arr.reduce( callback( accumulator , currentValue , index, array ) , initialValue )
callback: 执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
-
accumulator 累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。
-
currentValue 数组中正在处理的元素。
-
index [可选] : 数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
-
array[可选]: 调用reduce()的数组
initialValue[可选]:作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
文件目录:
index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = 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
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
模块下的其中一个文件
import { getSessionObj, setSessionObj } from '@/utils/index'
import { fetchList, del } from "@/api/classify";
let sessionKey = 'activeType'
const state = {
active: getSessionObj(sessionKey),// 当前选中的类型
lists: [],// 树列表
}
const mutations = {
SET_ACTIVE: (state, data) => {
state.active = data
setSessionObj(sessionKey, data)
},
SET_LISTS: (state, data) => {
state.lists = data
},
}
const actions = {
// 获取树列表
getTreeData({ commit },id) {
return new Promise((resolve, reject) => {
fetchList(id).then(response => {
const { data } = response
commit('SET_LISTS', data.children)
resolve()
}).catch(error => {
reject(error)
})
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
getters.js文件
const getters = {
sidebar: state => state.app.sidebar,
size: state => state.app.size,
device: state => state.app.device,
visitedViews: state => state.tagsView.visitedViews,
cachedViews: state => state.tagsView.cachedViews,
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name,
introduction: state => state.user.introduction,
roles: state => state.user.roles,
permission_routes: state => state.permission.routes,
errorLogs: state => state.errorLog.logs,
activeMoldType: state => state.classify.active,
activeType:state=>state.skill.active,
item:state=>state.skill.item,
event:state=>state.skill.event
}
export default getters
页面内使用:
- main.js文件内进行引入并挂载
import store from './store'
...
new Vue({
el: '#app',
router,
store, // 挂载
render: h => h(App)
})
- 页面内可由 this.$store… 进行访问,也可在要使用的页面进行引入,直接使用 store…
…
更多vuex的使用可查阅 vuex官方文档,这里主要记录如何自动加载文件