自动化注册组件和自定义指令
在我们封装全局组件和封装全局指令后,需要在main.ts中频繁进行全局注册,以下将对这块进行优化
一、自动化注册组件
我们在进行组件注册时,使用的是下面这种形式:
app.component('组件名称',组件)
这样我们可以使用循环组件的形式来对组件进行注册
1.在components文件夹下创建index.ts文件
import aaa from "@/components/aaa.vue" import bbb from "@/components/bbb.vue" const allModuleComponent:any = {aaa,bbb} export default { install(app:any){ Object.keys(allModuleComponent).forEach(item=>{ app.component(item,allGlobalComponent[item]) }) } }
2.在main.ts中进行注册
import allModuleComponent from "@/components/index.ts" //注册插件 app.use(allModuleComponent)
这样我们就只需要在index.ts文件中引入组件即可自动进行全局组件注册。
二、自定义指令注册
自定义指令注册和上面的组件注册方法是一样的,只是将注册的方法给替换一下即可。
1.在自定义指令文件下创建index.ts
// a指令 import a from "./aa" // b指令 import b from "./b" const directives:any = { // 指令对象 a, b } // 自动化指令封装 export default { install(app:any){ Object.keys(directives).forEach(key=>{ app.directive(key, directives[key]) }) } }
2.在main.ts中进行注册使用
// 安装自定义指令 import order from "@/untils/order/index" app // 安装自定义指令 .use(order)