vue局部引入组件和全局引入组件
局部引入
vue系统中,
1.components在文件夹中创建Demo/index.vue,Demo2/index.vue组件;
Demo/index.vue:
Demo2/index.vue:
2.utils/index.js工具方法中添加方法:
export const importAll = ® => {
const cache = {}
r.keys().forEach((key) => (cache[key] = r(key)))
return cache
}
3.在需要引入组件的页面parent/index.vue
script.js
import { importAll } from ‘@/utils/index’
const allFile = importAll(require.context(‘…/…/…/src/components/’, true, /index.vue$/))//按照自己系统的路径配置
const componentAll = {}
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const key in allFile) {
const element = allFile[key].default
if (element.name) {//组件文件index.vue里面的name
componentAll[element.name] = element
} else {
console.error(‘该组件注册失败’, element)
}
}
export default({
name:‘parent’,
…
components: {
…componentAll,
},
…
})
index.vue直接引入
vue2全局引入
1.components在文件夹中创建Demo/index.vue,Demo2/index.vue组件;
Demo/index.vue:
Demo2/index.vue:
2.main.js全局引入
const componentsContext = require.context(‘./components’, true, /.vue$/);
const components = []
componentsContext.keys().forEach((component) =>{
const componentsEntity = componentsContext(component).default
components.push(componentsEntity)
})
const dashboardPlugin = {
install(Vue) {
components.forEach((com) =>{
com.name && Vue.component(com.name,com)
})
}
}
Vue.use(dashboardPlugin)
3.index.vue直接中使用
index.vue