vue3自定义v-loading指令directives

1.在项目的src下创建一个directives文件夹写相应的指令
directives自定义指令
2.比如自定义全局的v-loading 在文件下创建loading
loading的样式

<template>
  <div class="loading-container">
    <Loading size="300" />
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Loading } from 'vant';
export default defineComponent({
  components:{
    Loading
  },
  setup() {
    
  },
});
</script>
<style lang="scss" scoped>
.loading-container{
  text-align: center;
  width: 10.8rem;
  position: absolute;
  top: 50%;
  z-index: 66;
}
</style>

3.相应的js代码directives/loading/index.ts
js代码关键


import {createApp, 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 = instance;
    if (binding.value) {
      appendEl(el);
    }
  },
  updated(el,binding) {
    if (binding.value !== binding.oldValue) {
      binding.value ? appendEl(el) : removeEl(el); 
    }
  },
};

const appendEl = (el) =>{
  el.appendChild(el.instance.$el);
};

const removeEl = (el) =>{
  el.removeChild(el.instance.$el);
};

4.在directives/index.ts中导出
导出相应的指令

5.在main.ts中全局引用
main.ts全局引用

import * as directives from '@/directives';
Object.keys(directives).forEach(key => {
  app.directive(key, (directives as { [key: string ]: Directive })[key]);
});

最后:在相应的页面中使用
页面中使用自定义指令

Logo

前往低代码交流专区

更多推荐