认识Vue扩展插件

众所周知,在 Vue 开发中,实现一个功能可以有很多种方式可以选择,这依赖于 Vue 强大的功能(指令、混合、过滤、插件等),本文介绍一下插件的开发使用。

Vue 插件

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

  • 添加全局方法或者 property。如:vue-custom-element

  • 添加全局资源:指令/过滤器/过渡等。如 vue-touch

  • 通过全局混入来添加一些组件选项。如 vue-router

  • 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

  • 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

使用插件

vue引入的插件,如 element , 都需要提供 install 方法,因为 Vue.use() 方法会调用插件里的 install 方法

import Vue from 'vue'
import Element from 'element-ui'

Vue.use(Element)

全局组件

类似的
全局组件也是同样的做法,在 install 方法里面 进行 组件 注册

import ColorIconComponents from './iconColor.vue'

const ColorIcon = {
    install: function (Vue) {
        Vue.component('ColorIcon', ColorIconComponents)
    }
}

export default ColorIcon

绑定prototype

数组对象等绑定自定义方法

// path: src/utils/customFn.js
export default {
  install(Vue) {
    // 数组对象排序 asc-升序 des-降序
    Array.prototype.sortListObjByKey = function (key, order = 'asc') {
      const that = this
      const comparefn = (obj1, obj2) => {
        if (order === 'asc') {
          return obj1[key] - obj2[key]
        } else {
          return obj2[key] - obj1[key]
        }
      }
      return that.sort(comparefn)
    }
  }
}

使用

// path: src/main.js
import customFn from "./libs/customFn";

Vue.use(customFn)

开发插件范式

来源

Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

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

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

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}

🎈🎈🎈

🌹 持续更文,关注我,你会发现一个踏实努力的宝藏前端😊,让我们一起学习,共同成长吧。

🎉 喜欢的小伙伴记得点赞关注收藏哟,回看不迷路 😉

🎁 欢迎大家评论交流, 蟹蟹😊

Tags: