【无标题】

vue局部引入组件和全局引入组件

局部引入

vue系统中,
1.components在文件夹中创建Demo/index.vue,Demo2/index.vue组件;
Demo/index.vue:

demo

Demo2/index.vue:

demo2

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:

demo

Demo2/index.vue:

demo2

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值