首页 > 其他分享 >写一个加载中的自定义指令

写一个加载中的自定义指令

时间:2022-10-13 10:33:59浏览次数:41  
标签:el loading const 自定义 binding instance 指令 加载

前置知识

el:指令绑定到的元素
binding:对象

  • value:传递给指令的值
  • arg:传递给指令的参数
  • instance:使用该指令的组件实例

首先构建自定义指令的样子

<template>
  <div class="loading">
    <div class="loading-content">
      <img width="24" height="24" src="./loading.gif">
      <p class="desc">{{title}}</p>
    </div>
  </div>
</template>

//loading在页面上垂直居中
<style lang="scss" scoped>
  .loading {
    position: absolute; 
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
</style>

loading的位置依赖于最近的非 static 定位祖先元素的偏移,所以需要给v-loading指令作用的dom,动态添加非static的position属性。

让loading挂载在自定义指令上

const loadingDirective = {
    mounted(el,binding) {
        const app = createApp(Loading) //创建Loading实例
        const instance = app.mount(document.createElement('div')) //将实例挂载到div中
        el.instance = instance //将instance挂载在el上,以便在其他作用域也可以访问到instance
        const title=binding.arg
        if (typeof title !== undefined) {
            instance.setTitle(title)
        }
        if (binding.value) { //loading的值
            append(el)
        }
    },
    updated(el, binding) {
        const title=binding.arg
        if (binding.value !== binding.oldValue){
            binding.value ? append(el) : remove(el)
        }
    },
}

function append(el) {
    const style = getComputedStyle(el)
    // debugger
    if (['fixed', 'relative', 'absolute'].indexOf(style.position)===-1) {
        addClass(el,relativeCls)
    }
    el.appendChild(el.instance.$el)
}
function remove(el) {
    removeClass(el,relativeCls)
    el.removeChild(el.instance.$el)
}

export default loadingDirective

添加样式&&移除样式

export function addClass(el, className) {
  if (!el.classList.contains(className)) {
    el.classList.add(className)
  }
}

export function removeClass(el, className) {
  el.classList.remove(className)
}

全局注册和局部注册

在main.js
app.directive('loading', loadingDirective)
在组件中

export default {
  directives: {
    loading: {
      /* ... */
    }
  }
}

在异步请求数据时使用

<template>
  <div class="recommend" v-loading="loading">
</template>

export default {
  computed: {
      loading() {
        return !this.sliders.length && !this.albums.length //在请求数据时,loading为true
      }
    },
}

标签:el,loading,const,自定义,binding,instance,指令,加载
From: https://www.cnblogs.com/poco-o/p/16787278.html

相关文章