1 -「全局组件注册」
组件是我们非常常用的东西,很多人使用组件都是通过一个一个文件去引用和注册。如果一个组件在整个项目里面的使用次数较多,每一次使用都需要引用并注册,就会显得特别麻烦
<template>
<div>
<h1>I am HelloWorld</h1>
<Child1></Child1>
</div>
</template>
<script>
import Child1 from './child1.vue' // 引入
export default {
name: 'HelloWorld',
data(){
return{
}
},
components:{ // 注册
Child1
},
props: {
msg: String
},
methods:{
}
}
</script>
<style scoped lang="less">
</style>
当我们在项目需要重复多次使用该组件,会导致出现很多重复的引入和注册代码,既繁琐又不雅观。因此我们可以通过一个全局的Js文件来管理,将需要多次使用的组件进行全局注册
创建全局.js文件管理全局组件
// 1 - globalComponent.js
import Vue from 'vue' // 引入vue
// 处理首字母大写 abc => Abc
function changeStr(str){
return str.charAt(0).toUpperCase() + str.slice(1)
}
/*
require.context(arg1,arg2,arg3)
arg1 - 读取文件的路径
arg2 - 是否遍历文件的子目录
arg3 - 匹配文件的正则
关于这个Api的用法,建议小伙伴们去查阅一下,用途也比较广泛
*/
const requireComponent = require.context('.', false, /\.vue$/)
console.log('requireComponent.keys():',requireComponent.keys()) // 打印
requireComponent.keys().forEach(fileName => {
const config = requireComponent(fileName)
console.log('config:',config) // 打印
const componentName = changeStr(
fileName.replace(/^\.\//, '').replace(/\.\w+$/, '') // ./child1.vue => child1
)
Vue.component(componentName, config.default || config) // 动态注册该目录下的所有.vue文件
})
// 2 - 将globalComponent.js引入main.js
import global from './components/globalComponent'
// 3 - 使用这类组件不再需要引入和注册,直接标签使用即可
<template>
<div>
<h1>I am HelloWorld</h1>
<Child1></Child1>
</div>
</template>