家喻户晓,在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.jsexport 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.jsimport 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) { // 逻辑... }}
继续更文,关注我,你会发现一个虚浮致力的宝藏前端,让咱们一起学习,独特成长吧。
喜爱的小伙伴记得点赞关注珍藏哟,回看不迷路
欢送大家评论交换, 蟹蟹