vue3 封装插件,以 loading 为例

// main.js
import Loading from "@/plugins/loading";
import app from "@/plugins/appInstance";
app.use(Loading).mount("#app");
// 使用
app.config.globalProperties.$loading.show();
app.config.globalProperties.$loading.hide();
// loading.js
import {
  createApp,
  reactive
} from "vue";
import Loading from "@/components/Loading.vue";

const conifg = reactive({
  show: false
});
const instance = createApp(Loading, {
  conifg
}).mount(document.createElement("div"));

const load = {
  show() {
    conifg.show = true;
    document.body.appendChild(instance.$el);
  },

  hide() {
    conifg.show = false;
  }
};
console.log(instance);

export default {
  install(app) {
    app.config.globalProperties.$loading = load;
  }
};

<!-- loading.vue -->
<template>
  <Overlay class-name="car-loading" :show="props.conifg.show">
    <div class="loading-wrapper" @click.stop>
      <div class="loading-icon">
        <div class="circle"></div>
        <div class="content"></div>
        <img class="car-img" src="@/assets/images/car-loading.png" alt />
      </div>
      <p class="loading-text">加载中...</p>
    </div>
  </Overlay>
</template>
<script setup>
import { Overlay } from "vant";
const props = defineProps({ conifg: { type: Object } });
</script>

<style lang='scss' scoped>
.row-column-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.car-loading {
  background: rgba($color: #000000, $alpha: 0.5);
}
.loading-wrapper {
  width: 160px;
  height: 160px;
  background: rgba($color: #000000, $alpha: 0.5);
  border-radius: 20px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  padding: 26px 0;

  .loading-icon {
    @extend .row-column-center;
  }

  .loading-text {
    font-size: 14px;
    color: #ffffff;
    letter-spacing: -0.15px;
    line-height: 14px;
    margin-top: 13px;
    text-align: center;
  }
  .car-img {
    width: 40px;
    height: 30px;
    position: absolute;
  }

  .content {
    width: 64px;
    height: 64px;
    background: var(--van-blue);
    border-radius: 50%;
    @extend .row-column-center;
    position: absolute;
  }

  .circle {
    width: 75px;
    height: 75px;
    border: 1px solid var(--van-blue);
    border-radius: 50%;
    @extend .row-column-center;
    transform-origin: center;
    animation: rotate 1s infinite linear;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      top: -4px;
      left: calc(50% - 3px);
      width: 6px;
      height: 6px;
      background: var(--van-blue);
      border-radius: 50%;
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  50% {
    transform: rotate(180deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>