Vue3-lottie + v-loading 初步使用

462 阅读1分钟

Vue3-lottie

该库是一个动画库,可以导入一些json格式的动画进行使用

安装

组件使用可以参考文档,这里就不展示了

npm install vue3-lottie@latest --save

v-loading 指令封装

<template>
  <div class="loading-box">
	<!-- width:宽度,height:高度,animationData:加载的json文件 -->
	  <Vue3Lottie width="200px" height="200px" :animationData="loading01" />
  </div>
</template>

<script setup>
// 详细介绍https://www.npmjs.com/package/vue3-lottie
import {Vue3Lottie} from "vue3-lottie";
import loading01 from "@/assets/json/loading01.json"

</script>

<style scoped lang="scss">
.loading-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(0 0 0 / 20%);

  position: absolute;
  top: 0;
  left: 0;
  :deep(.ant-spin-dot-item) {
    background-color: #fff;
  }
  :deep(.ant-spin.ant-spin-show-text .ant-spin-text) {
    color: #fff;
  }
}
</style>

index.js

import { createApp } from "vue";
import Loading from "./index.vue";

const loading = {
  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) => {
  // 给父元素加个定位,让loading元素定位
  el.style.position = "relative";
  el?.appendChild(el.instance.$el);
};
// 移除元素
const removeEl = (el) => {
  el.style.position = "";

  // 踩坑:el?.removeChild(el.instance.$el)->直接这样写会报错:Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.(要删除的节点不是此节点的子节点)
  // 解决:判断一下是否为此节点的子元素再移除(参考:https://www.freesion.com/article/2620879355/)
  let $el = el.instance.$el;
  if (el?.contains($el)) {
    el?.removeChild($el);
  }
};

export default loading;

实现效果

image.png