webpack的require.context在vue2中常见的应用场景

require.context是webpack的一个api,可以在前端工程化里提高开发效率
如下图,接受4个参数,一个参数是目录(字符串),第二个参数是是否包含子目录(布尔值),第三个参数:过滤,传正则表达式,第四> 个参数是模式,有5个参数可选,默认sync

require.context(
  (directory: String),
  (includeSubdirs: Boolean) /* optional, default true */,
  (filter: RegExp) /* optional, default /^\.\/.*$/, any file */,
  (mode: String) /* optional, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once', default 'sync' */
);

批量注册公共组件

import Vue from 'vue';

const requireComponent = require.context(
    // 其组件目录的相对路径
    './components/GlobalComponents',
    // 是否查询其子目录
    true,
    // 匹配基础组件文件名的正则表达式
    /\w+\.vue$/,
);
requireComponent.keys().forEach((fileName) => {
    // 获取组件配置
    const componentConfig = requireComponent(fileName);

    // 获取组件的 PascalCase 命名
    const componentName = fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '');

    // 全局注册组件
    Vue.component(
        componentName,
        // 如果这个组件选项是通过 `export default` 导出的,
        // 那么就会优先使用 `.default`,
        // 否则回退到使用模块的根。
        componentConfig.default || componentConfig,
    );
});

公共组件的使用

<Title(文件名称) 传参/>

批量导入带命名空间的vuex的不同模块

import vue from 'vue';
import Vuex from 'vuex';

// 自动注入
const storeFiles = require.context('./modules', false, /\.js$/);
const modules = {};
storeFiles.keys().forEach((fileName) => {
    const moduleName = fileName.replace(/(\.\/|\.js)/g, '');
    modules[moduleName] = {
        namespaced: true,
        ...storeFiles(fileName).default,
    };
});
vue.use(Vuex);
export default new Vuex.Store({
    state: {},
    getters: {},
    mutations: {},
    actions: {},
    modules,
});

可以在同级目录底下创建一个modules目录,里面放n个js文件
在这里插入图片描述
js文件放上global.js

const global = {
    state: () => ({
        // 项目标题
        title: '',
    }),

    getters: {
    },

    mutations: {
        setTitle(state, param) {
            state.title = param;
        },
    },

    actions: {
    },
};

export default global;

访问 / 更改 vuex值的时候

  • 常规访问
this.store.state.global.title;
this.store.commit('global/titie', '设置新值');
  • mapState 辅助函数
import { mapState } from 'vuex';
computed: {
    ...mapState({
        title: state => state.global.title,
    })
},
mounted() {
    console.log('title', this.title);
},
methods: {
	...mapMutations('global', [
       'setTitle',
   ])
},
  • 使用 createNamespacedHelpers 创建基于某个命名空间的辅助函数
import { createNamespacedHelpers } from 'vuex';
const { mapState, mapMutations } = createNamespacedHelpers('global'); // 如果模块处于子模块的话,加/号

computed: {
    ...mapState({
        title: state => state.title,
    });
    this.setTitle('设置新值');
},
methods: {
    ...mapMutations([
        'setTitle',
    ]);
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值