Vue 封裝 loading 外掛

我是小卡車呀發表於2020-12-11

具體屬性:

this.$loading(option: Object): Object -> close();

option 屬性:

屬性名型別描述預設值
eleDOM元素要新增載入的DOM元素document.body
messageString載入顯示的文字“loading…”
colorString載入顯示文字顏色“#000000”
iconfontString載入文字前方顯示的 iconfont 類名(“icon-xxx”)“”
backgroundColorString載入背景顏色(建議使用 rgba)“rgba(44, 62, 80, .7)”

程式碼如下:

vp-loading.vue

<template>
  <div class="vp-loading" >
    <span :class="'iconfont ' + iconfont"></span>{{ message }}
  </div>
</template>

<script>
export default {
  name: "VpLoading",
  props: {
    message: {
      type: String,
      default: ""
    },
    iconfont: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
    }
  },
  created() {

  },
  mounted() {

  }
}
</script>
<style scoped>
.vp-loading {
  position: fixed;
  z-index: 999;
  top: 0px;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: rgba(44, 62, 80, .7);
  display: flex;
  justify-content: center;
  align-items: center;
}
.iconfont {
  margin-right: .2rem
}
</style>

loading.js

import VpLoading from "./vp-loading.vue";

let loading = {};

loading.install = Vue => {
  Vue.prototype.$loading = function(option = {}) {
    let options = {
      ele: option && option.ele || document.body,
      message: option && option.message || "loading...",
      color: option && option.color || "#000000",
      iconfont: option && option.iconfont || "",
      backgroundColor: option && option.backgroundColor || "rgba(44, 62, 80, .7)" // 建議使用 rgba 格式,並設定透明度
    }
    let vploadingInstance = Vue.extend(VpLoading);
    let vploading
    let loadingEle = document.createElement("div");
    let loadEle;
    Vue.nextTick().then(() => {
      vploading = new vploadingInstance({
        propsData: {
          message: options.message,
          iconfont: options.iconfont
        }
      });
      vploading.$mount(loadingEle);
      let el = vploading.$el;
      loadEle = options.ele;
      if (loadEle !== document.body) {
        loadEle.setAttribute("style", "position: relative");
        el.setAttribute("style", "position: absolute; top: 0; right: 0; left: 0; bottom: 0")
      }
      el.style.color = options.color;
      el.style.backgroundColor = options.backgroundColor;

      loadEle.appendChild(el);
    });

    return {
      close: () => {
        vploading.$el.remove();
      }
    };
  };
};

export default loading;

main.js

import vploading from  './components/loading';
Vue.use(vploading);

元件內部使用

mounted() {
  let loadObj = this.$loading({
    // ele: document.getElementsByClassName("test")[0],
    color: "#00a8ff",
    iconfont: "icon-redupaixu",
  });
  setTimeout(() => {
    loadObj.close();
  }, 3000);
},

相關文章