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

前置知识

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挂载在自定义指令上

在mounted这个钩子中

const loadingDirective = {
    mounted(el,binding) {
        const app = createApp(Loading) //创建Loading实例
        const instance = app.mount(document.createElement('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) { //确定loading水平垂直居中
        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
      }
    },
}
posted @ 2022-10-13 10:28  pocoui  阅读(29)  评论(0)    收藏  举报