vue loading 插件编写与实战

  在没有封装组件之前,如果不使用第三方插件,那么很多情况下我们会编写几个常用的组件来提供给页面使用,如Alert/Loading组件,而你可能需要在很多页面中引入并且通过components注册组件,但是像这样使用率很高的组件一般我们希望全局注册后直接就可以在相应页面使用,因此我们需要将他们封装成插件。

  vue插件的编写方法一般分为4类,如上图所示。主要注册与绑定机制如下:

export default {
    install(Vue, options) {
        Vue.myGlobalMethod = function () {  // 1. 添加全局方法或属性,如:  vue-custom-element
            // 逻辑...
        }

        Vue.directive('my-directive', {  // 2. 添加全局资源:指令/过滤器/过渡等,如 vue-touch
            bind (el, binding, vnode, oldVnode) {
                // 逻辑...
            }
            ...
        })

        Vue.mixin({
            created: function () {  // 3. 通过全局 mixin方法添加一些组件选项,如: vuex
                // 逻辑...
            }
            ...
        })    

        Vue.prototype.$myMethod = function (options) {  // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现
            // 逻辑...
        }
    }
}

  实战:loading

//loading.vue
<template> <div class="loading-box" v-show="show"> <div class="loading-mask"></div> <div class="loading-content"> <div class="animate"> </div> <div class="text">{{text}}</div> </div> </div> </template> <script> export default { props: { show: Boolean, text: { type: String, default: '正在加载中...' }, } } </script>
<style>
  ...
</style>

下面我们便来封装一下该组件:

// loading.js
import LoadingComponent from './components/loading.vue'

let $vm

export default {
    install(Vue, options) {
        if (!$vm) {
            const LoadingPlugin = Vue.extend(LoadingComponent);

            $vm = new LoadingPlugin({
                el: document.createElement('div')
            });

            document.body.appendChild($vm.$el);
        }

        $vm.show = false;

        let loading = {
            show(text) {
                $vm.show = true;

                $vm.text = text;
            },
            hide() {
                $vm.show = false;
            }
        };

        if (!Vue.$loading) {
            Vue.$loading = loading;
        }

        // Vue.prototype.$loading = Vue.$loading;

        Vue.mixin({
            created() {
                this.$loading = Vue.$loading;
            }
        })
    }
}

  目录结构:

 

  首页:this.$loading.show('')       this.$loading.hide()

created () {
  this.$loading. show( '')
    axios. get(url.getIconList). then( res => {
      if (res.status === 200) {
        this.iconList = res.data.iconlist
        this.$loading. hide()
      }
    }). catch( error => {
      console. log(error)
    })
}

猜你喜欢

转载自www.cnblogs.com/sunjuncoder/p/9900079.html