文章目录
- 1. 创建指令文件
- 2. 全局注册
- 3. 使用
1. 创建指令文件
src/directives
在directives中创建如下文件
src│─directives│ index.ts└─loadingindex.tsindex.vue
- directives/ index.ts
export * from './loading'
- directives/loading/index.ts
import { createApp } from 'vue'
import type { Directive } from 'vue'
import Loading from './index.vue'
// 注册组件
export const loading: Directive = {mounted(el, binding) {const app = createApp(Loading)const instance = app.mount(document.createElement('div'))el.instance = instanceif (binding.value) {appendEl(el)}},updated(el, binding) {if (binding.value !== binding.oldValue) {binding.value ? appendEl(el) : removeEl(el)}}
}
// 插入元素
const appendEl = (el: any) => {// 给父元素加个定位,让loading元素定位el.style.position = 'relative'el?.appendChild(el.instance.$el)
}
// 移除元素
const removeEl = (el: any) => {el.style.position = ''const $el = el.instance.$elif (el?.contains($el)) {el?.removeChild($el)}
}
- directives/loading/index.vue
<template><div class="loading-box"><Spin tip="Loading" /></div>
</template><script lang="ts" setup>javascript">
import {Spin} from "ant-design-vue";
</script><style scoped lang="less">
.loading-box {width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;background: rgba(255,255,255,0.2);position: absolute;top: 0;left: 0;:deep(.ant-spin-dot-item) {background-color:#f55345;}:deep(.ant-spin.ant-spin-show-text .ant-spin-text) {color: #f55345;}
}
</style>
2. 全局注册
src/main.ts
import './assets/style/main.less'
import { createApp, type Directive } from 'vue'
import App from './App.vue'
import * as directives from './directives'const app = createApp(App)
// 循环注册指令
Object.keys(directives).forEach(key => {app.directive(key, (directives as { [key: string]: Directive })[key])
})
app.mount('#app')
3. 使用
注册成功之后就可以在全局范围内使用了
<div v-loadin="true"></div>