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)
    })
}

posted @   sunjun_coder  阅读(4856)  评论(4编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示