webpack require.context

复制代码
require.context(
  (directory: String),
  (includeSubdirs: Boolean) /* 可选的,默认值是 true */,
  (filter: RegExp) /* 可选的,默认值是 /^\.\/.*$/,所有文件 */,
  (mode: String)  /* 可选的, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once',默认值是 'sync' */
)

指定一系列依赖项,通过使用 directory 的路径,以及 includeSubdirsfilter 选项,进行更细粒度的模块引入,使用 mode 定义加载方式。以此可以很容易的解析模块:

复制代码
var context = require.context('components', true, /\.html$/);
var componentA = context.resolve('componentA');

如果 mode 设置为 lazy,基础模块将以异步方式加载:

复制代码
var context = require.context('locales', true, /\.json$/, 'lazy');
context('localeA').then((locale) => {
  // do something with locale
});

mode 的可用模式及说明的完整列表在 import() 文档中进行了描述。

  • keys {Function} -返回匹配成功模块的名字组成的数组
  • id {String} -执行环境的id,返回的是一个字符串。
  • resolve {Function} -接受一个参数request,request为检索的文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径

生成自动路由用例:

const reqRouter = require.context('@/views', true, /\.vue$/)

javascript 复制代码
// 自动加载路由
const autoLoadRoutes = [];
 
// 自动加载
reqRouter.keys().forEach(key => {
  let reqRouterDefault = reqRouter(key).default
  if (!reqRouterDefault.commonComponent) {      //公共组件不参与路由配置,公共组件配置true
    let fileUrl = key.replace(/\.\//g, '')//匹配路径
    let routePath = fileUrl.split('.')[0];
    autoLoadRoutes.push({
      path: `/${routePath}`,
      name: routePath,
      meta: {
        title: reqRouterDefault.title,
        keepAlive: reqRouterDefault.keepAlive
      },
      component: () => import(`@/views/${fileUrl}`)
    })
  }
})
// 全部路由信息
const routes = [
  {
    path: '/',
    redirect: 'home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views//Home.vue')
  },
  {
    path: '/401',
    name: '401',
    component: () => import('@/views//Unauthorized.vue')
  },
  ...autoLoadRoutes,
]

store合成用例:

store js中的代码示例

javascript 复制代码
const state = {
  test: 0
}

const mutations = {
  CHANGE_TEST: (state, payload) => {
    state.test= payload
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
相关推荐
^小桃冰茶2 小时前
CSS知识总结
前端·css
运维@小兵2 小时前
vue注册用户使用v-model实现数据双向绑定
javascript·vue.js·ecmascript
巴巴_羊3 小时前
yarn npm pnpm
前端·npm·node.js
chéng ௹4 小时前
vue2 上传pdf,拖拽盖章,下载图片
前端·css·pdf
嗯.~4 小时前
【无标题】如何在sheel中运行Spark
前端·javascript·c#
A_aspectJ7 小时前
【Bootstrap V4系列】学习入门教程之 组件-输入组(Input group)
前端·css·学习·bootstrap·html
兆。7 小时前
电子商城后台管理平台-Flask Vue项目开发
前端·vue.js·后端·python·flask
互联网搬砖老肖7 小时前
Web 架构之负载均衡全解析
前端·架构·负载均衡
sunbyte8 小时前
Tailwind CSS v4 主题化实践入门(自定义 Theme + 主题模式切换)✨
前端·javascript·css·tailwindcss
风之舞_yjf9 小时前
Vue基础(8)_监视属性、深度监视、监视的简写形式
javascript·vue.js·ecmascript