vue3.x+ts 自定义加载指令-花瓣加载组件
修改以前写的2.x的加载指令
加载组件 loadingComponent/LoadingComponent1.vueclass="LoadingComponent" v-show="visible">class="modal">class="out">class="fade-in">class="container">class="one common">class="two common">class="three common">class="four common">class="five common">class="six common">class="seven common">class="eight common">
指令定义文件 loadingComponent/index.ts
import LoadingComponent from './LoadingComponent1.vue' import { createApp, nextTick, } from "vue"; const appndChild = (el: any) => { el.appendChild(el.instance.$el); } const remove = (el: any) => { el.removeChild(el.instance.$el); } const toggleLoading = (el, binding) => { if (binding.value) { nextTick(() => { // 控制loading组件显示 el.instance.visible = true // 插入到目标元素 appndChild(el) }) } else { el.instance.visible = false remove(el) } } export default { mounted(el: any, bind: any) { const app = createApp(LoadingComponent); const instance: any = app.mount(document.createElement("div")); el.instance = instance; if (bind.value) { toggleLoading(el, bind) } }, updated(el: any, bind: any) { if (bind.value !== bind.oldValue) { toggleLoading(el, bind) } }, onUnmounted(el, bind: any) { el.instance && el.instance.$destroy() } }
指令注册 index.ts
import myLoadingDirective from "./loadingComponent"; export default (app) => { //自定义组件 app.directive('myLoading', myLoadingDirective) }
main.ts
import loadingdirectives from './directive/loading' loadingdirectives(app)
使用
v-myLoading="loadingState"