Vue 自定义v-loading指令开发

步骤1. derective.js中

/*  
  vue自定义指令
*/

import { createApp } from "vue"
import Loading from './loading.vue'

const relativeCls = 'g-relative'

const loadingDirective = {
  mounted(el, binding) {
    const app = createApp(Loading)  //app挂载到Loading
    const instance = app.mount(document.createElement('div')) //创建html-div实例
    el.instance = instance //保留instance

    const title = binding.arg //使用动态参数实现title传入loading页面
    if(typeof title !== 'undefined'){
      instance.setTitle(title)
    }
    
    if(binding.value){ // loading=true 追加
      append(el)
    }
  },
  updated(el, binding) {
    const title = binding.arg //实现title传入loading页面
    if(typeof title !== 'undefined'){
      el.instance.setTitle(title)
    }
    if(binding.value != binding.oldValue) {
      binding.value ? append(el) : remove(el)
    }
  },
}

function append(el){  // 追加函数
  const style = getComputedStyle(el)
  if (['absolute', 'fixed', 'relative'].indexOf(style.position) === -1) {
    el.classList.add(relativeCls) //添加relative类(方便loading居中)
  }
  el.appendChild(el.instance.$el) // $el参数指向应用指令的dom
}

function remove(el){    //追加函数
    el.classList.remove(relativeCls)  //移除relative类
    el.removeChild(el.instance.$el) 
}

export default loadingDirective

步骤2. main.js中

  import loadingDirective from '@/directive/loading/directive' //引入指令
  app.directive('loading', loadingDirective)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值