全局方法或property,如:vue-custom-element指令、过滤器、过度等,如:vue-touchVue.prototype上实现// 调用 myPlugin.install(Vue)
Vue.use(myPlugin)
new Vue({
// ...组件选项
})Vue.use(myPlugin,{someOptions:true})vue-router,在检测到 Vue是可访问的全局变量时,会自动调用Vue.use(),然而在像CommonJS这样的模块环境中,你应该始终显式的调用Vue.use()
// 用 Browserify 或 webpack 提供的 CommonJS 模块环境时
const Vue = require('vue')
const VueRouter = require('vue-router')
//别忘了调用此方法
Vue.use(VueRouter )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) { // 逻辑... } }对象,必须提供 install方法,如果插件是一个函数,它会被作为install方法,install方法调用是,会将Vue作为参数传入##### 所以,Vue.use的参数必须是一个Object对象或者function函数,如果是对象的话,必须要提供install方法,之后会将Vue作为参数传入
import { toArray } from '../util/index'
// Vue.use 源码
export function initUse (Vue: GlobalAPI) {
// 首先先判断插件plugin是否是对象或者函数:
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
// 判断vue是否已经注册过这个插件,如果已经注册过,跳出方法
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// 取vue.use参数,toArray() 方法代码在下一个代码块
const args = toArray(arguments, 1)
args.unshift(this)
// 判断插件是否有install方法,如果有就执行install()方法。没有就直接把plugin当Install执行。
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}// toArray 方法源码
export function toArray (list: any, start?: number): Array<any> {
start = start || 0
let i = list.length - start
const ret: Array<any> = new Array(i)
while (i--) {
ret[i] = list[i + start]
}
return ret
}`plugin: Function | Object` const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
// 判断vue是否已经注册过这个插件,如果已经注册过,跳出方法
if (installedPlugins.indexOf(plugin) > -1) {
return this
}const args = toArray(arguments, 1)
args.unshift(this) if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}installedPlugins.push(plugin)原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。