vue的全局loading封装

571 阅读1分钟

components文件夹下新建如下文件结构

image.png

.vue文件

  <div class="loading_wrapper" v-show="isShowLoading">
    <div class="content">
      <p>{{ title }}</p>
      <br />
      <i class="el-icon-loading"></i>
      <!--
        <img :src="require('../../../assets/hicling/tits.gif')" alt="loading">
      -->
    </div>
  </div>
</template>
<script>
export default {
  name: "Loading",
  data() {
    return {
      title: "loading...",
      isShowLoading: false
    };
  },
  methods: {
    show(title) {
      this.isShowLoading = true;
      if(title){
        this.title = title;
      }
    },
    hide() {
      this.isShowLoading = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.loading_wrapper {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 0.18rem;
  color: #fff;
  z-index: 9999;
  .content {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    
      font-size: .28rem;
      color: rgb(83, 83, 196);
    
  }
}
</style>

index.js文件

import Vue from 'vue';

const _Loading = Vue.extend(Loading);
let instance = undefined;

function LoadingConstructor(){
  Vue.prototype.$_loading = {
    show(title){
      if(!instance){
        const odiv = document.createElement('div');
        const oapp = document.getElementById('app')
        oapp.appendChild(odiv);
        instance = new _Loading();
        instance = instance.$mount(odiv);
        instance.show(title)
      }else{
        instance.show(title)
      }
    },
    hide(){
      if(!instance){
        return
      }
      instance.hide();
    }
  }
}
export default LoadingConstructor;

不知道这个方式合不合理 欢迎大佬指导