vue中如何优雅的注册全局组件
//首先写一个组件(login.vue)
<template>
<div class="login">
<h1>login</h1>
</div>
<template>
<script>
export default {
name : 'login',
props: {
msg:String
}
}
</script>
<style scoped>
</ style>
//在helloworld中使用
<template>
<div class="hello">
<h1>Hello World</h1>
<Login />
</div>
<template>
<script>
import Login from './login.vue'
export default {
name : 'helloworld',
props: {
msg:String
},
components:{
Login
}
}
</script>
<style scoped>
</ style>
优化
新建一个global.js文件
import Vue from 'vue'
function changeStr(str){
//charAt 取字符的第一个字节 abc => Abc
return str.charAt(0).toUpperCase() + str.slice(1)
}
const requireComponent = require.context('.',false,/\.vue$/)
requireComponent.keys().forEach(fileName =>{
const config =requireComponent(fileName)
const componentName = changeStr(
fileName.replace(/^\.\//,'')
)
Vue.component(componentName,config.default || congig)
})
然后在main.js 中引用’
import global from'./components/global.js'
require.context 是什么?
require.context