Vue全局组件注册+require.context()函数

Vue全局组件注册+require.context()函数

在一个项目中,如果某些组件频繁的使用,我们则需要频繁的引入和注册,我们可以通过require.context()函数匹配到这些组件统一进行全局注册。

1. 创建globalComp.js文件
目录结构:
在这里插入图片描述

// 1. globalComp.js
import Vue from 'vue'

// 处理首字母大写 abc => Abc
function changeStr(str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

/*
  require.context()函数的作用: 匹配一个文件夹下所有符合规则的文件

  require.context()函数接收三个参数:
  1.directory{String} - 文件夹路径
  2.useSubdirectories{Boolean} - 是否遍历文件的子目录
  3.regExp{RegExp} - 匹配文件的正则
*/
/*
  require.context()函数执行后返回一个函数,并且这个函数有三个属性:
  1.id{String} - 执行环境的id,返回的是一个字符串
  2.keys{Function} - 返回匹配成功的所有文件的相对路径组成的数组
  3.resolve{Fuction} - 接受一个参数request,request为文件夹下面匹配成功文件的相对路径,返回这个匹配文件相对于整个工程的相对路径
*/ 
const files = require.context('.', false, /\.vue$/);
console.dir(files);
console.log(files.id);
console.log(files.keys());
console.log(files.resolve(files.keys()[0]));

files.keys().forEach(fileName => {
  // files作为一个函数,也接受一个参数request,这个和resolve方法的request参数是一样的,即匹配文件的相对路径,而files函数返回的是一个模块,这个模块才是我们想要的
  const module = files(fileName);
  console.log('module:' + module);
  const compName = changeStr(
    fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')  //  ./Child1.vue => Child1
  )

  Vue.component(compName, module.default || module)  // 动态注册该目录下所有的.vue文件
});

2. 将globalComp.js引入main.js中

import Vue from "vue";
import App from "./App.vue";
import router from "./router/router";
import store from "./store/store";
// 2.将globalComp.js引入main.js中
import global from './components/globalComp'

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

3. 使用这类组件不再需要导入和注册,直接标签使用即可

<template>
  <div id="app">
    <!-- 3.使用这类组件不再需要导入和注册,直接标签使用即可 -->
    <Child1></Child1>
    <Child2></Child2>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>
*::selection {
  background-color: rgba(0, 0, 0, 0);
}
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值