制作一个vue插件

平时在使用loading、消息弹窗这种通用的组件,如果用一次就引入一次很不方便,于是查阅了一下vue的官方文档找到了插件的制作方法。

  • Vue.js 的插件应当有一个公开方法 install 。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象
MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}
  • 使用插件只需要在 main.js 中引入,再通过全局方法 Vue.use() 注册插件,Vue.use 会自动阻止多次注册相同插件,届时只会注册一次该插件。
// 用 Browserify 或 webpack 提供的 CommonJS 模块环境时
var Vue = require('vue')
var VueRouter = require('vue-router')

// 不要忘了调用此方法
Vue.use(VueRouter)

看了文档之后思路并不是很清晰,于是又再 github 上面阅读了一下 vuxloading 插件的源码,按着 vux 的思路自己仿照着制作了一个 loading 插件

https://github.com/airyland/vux/blob/v2/src/plugins/loading/index.js
https://github.com/airyland/vux/blob/v2/src/components/loading/index.vue

  • 首先写一个正常的组件 loading.vue,需要被获取到的变量写到 props
<template>
    <div v-if="isShow" class="loading-wrap">
        <img src="../images/loading.gif" alt="loading...">
    </div>
</template>

<script>
export default {
    props: {
        isShow: Boolean,
    }
}
</script>

<style lang="scss">
    @import '../../../style/mixin';

    .loading-wrap {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999999999;
        background-color: rgba(0, 0, 0, 0.1);
        img { @include center; width: 3rem;
        }
    }
</style>
  • 开始制作插件 index.js
import LoadingComponent from './loading'

let $vm

const plugin = {
  install (Vue, options) {
    const Loading = Vue.extend(LoadingComponent)

    // 防止重复安装插件
    if (!$vm) {
      $vm = new Loading({
        el: document.createElement('div')
      })
      document.body.appendChild($vm.$el)
    }

    const loading = {
      show () {
        $vm.isShow = true
      },
      hide () {
        $vm.isShow = false
      },
      status () {
        return $vm.isShow
      }
    }

    if (!Vue.$loading) {
        // 将loading挂载到Vue实例上
        Vue.$loading = loading;
    }

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

export default plugin

全局注册插件 main.js

// 引入index.js
import Loading from './loading/index'
// 注册
Vue.use(Loading)

使用插件

  • 因为是全局插件,所以在项目任意地方都可以使用。省去了引入的步骤非常方便。在 vue 文件中可以通过 this.$loading 来访问我们挂载到Vue上的一些方法,如果是再 js 文件中可以通过 window.appVue.$loading 来访问。

以上就是制作一个简单插件的方法,个人水平有限如果有不对的地方,希望大家可以提出来,一起学习。

猜你喜欢

转载自blog.csdn.net/qq_41418386/article/details/81333561