实现一个vue-loading插件 | 进度条样式

1,956 阅读1分钟

通过添加实例方法,手写插件

vue插件的编写方法分为4类,此篇文章通过添加实例方法编写插件

export default {
    install(Vue, options){
        Vue.prototype.$myMethods = function (options){
            // 代码逻辑 添加实例方法,通过把它们添加到 Vue.prototype 上实现
        }
    }
}

插件封装成组件

如果我们在组件的基础上编写插件,我们可以使用Vue.extend(component)来进行,

loading插件实例

loading.vue组件

<template>
  <div class="loadings" v-show="isShow">
    <div class="c-loading">
      <div class="c-l-loading"></div><span>{{text}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
      }
    },
    props: {
      isShow: Boolean,
      text: {
        type: String,
        default:'正在加载中...'
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/style" scope>

  .loadings {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: rgba(0,0,0,0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    z-index: 10000;
     @keyframes mymove
      {
        from {width:0px;}
        to {width:300px;}
      }
      .c-loading{
        width:300px;
        height:5px;
        border-radius: 10px;
        position: relative;
        background:#f3f3f3;
        span{
          float: right;
          margin-right: -60px;
          margin-top: -10px;
        }
      }
      .c-l-loading{
        width:0px;
        height:5px;
        border-radius: 5px;
        background:#409EFF;
        animation:mymove 10s ease;
        animation-fill-mode:forwards;
      }
  }
</style>

封装该组件

loading.js

import loading from './loading.vue'

let $vm = null

export default{
  install(Vue, options){
    if(!$vm){
      let myLoading = Vue.extend(loading) //通过Vue.extend()方法创建了一个构造器

      $vm = new myLoading({ 
        el: document.createElement('div')
      }) //通过构造器创建$vm实例,并挂载在div上

      document.body.appendChild($vm.$el) //插入到Dom节点上
    }


    $vm.isShow = false  //创建一个属性来控制显隐

    let myMethods = {
      show(text) {
        $vm.isShow = true
        $vm.text = text
      },
      hide() {
        $vm.isShow = false
      }
    }

    if(!Vue.$vLoading){
      Vue.$vLoading = myMethods
      Vue.prototype.$vLoading = Vue.$vLoading  //添加实例方法
    }else{
      console.log('$vLoading方法已被占用')
    }
  }
}

插件写完之后,在main.js中全局注册一下该插件,通过Vue.use()即可使用该插件,其会自动调用install方法,Vue.use会自动阻止多次注册插件。

import Vue from 'vue'
import MyLoading from './loading.js'
Vue.use(MyLoading) 

全局注册完成之后,我们可以在页面中使用 this.$vLoadingshow() 来显示,使用 this.$vLoading.hide()来隐藏。