1. 使用
1.1 官网地址
1.2 插件使用方式
let MyPlugin = {
install(Vue, args) {
//逻辑...
}
};
let MyPlugin2 = function(Vue, args) {
//逻辑...
};
Vue.use(MyPlugin, {
options: "MyPlugin1"
});
Vue.use(MyPlugin2, {
options: "MyPlugin2"
});
1.3 demo
<!DOCTYPE html>
<html>
<head>
<title>Vue插件</title>
<!-- 填写vue地址 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 使用方式一 定义MyPlugin, MyPlugin是个对象,包含一个install属性,install对应一个函数。
let MyPlugin = {
install(Vue, args) { //Vue对应全局的Vue构造函数,用作后续的属性、指令、混入、原型对象的扩展
console.log(Vue, args)
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 逻辑...
}
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
}
// 使用方式二 定义MyPlugin2, MyPlugin2本身就是个函数
let MyPlugin2 = function (Vue, args) {
console.log(Vue, args)
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 逻辑...
}
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
</script>
</head>
<body>
<div id="demo">
<p>{{foo}}</p>
</div>
<script>
Vue.use(MyPlugin, {
options: "MyPlugin1"
})
Vue.use(MyPlugin2, {
options: "MyPlugin2"
})
const app = new Vue({
el: '#demo',
data: { foo: 'foo' }
})
</script>
</body>
</html>
2. 源码
/* @flow */
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) { //这里能看到Vue.use传入的plugin可以是函数也可以是对象
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) { //自动阻止多次注册相同插件,届时即使多次调用也只会注册一次该插件。
return this
}
// additional parameters
// Vue.use(MyPlugin, arg)
// install(Vue)
const args = toArray(arguments, 1) //获取Vue.use(plugin, args)中的args,args是用户传入的自定义配置项
args.unshift(this) // 往args前面插入当前Vue对象,所以后续的回调函数的第一个参数就是这个Vue对象
if (typeof plugin.install === 'function') {//如果传入的plugin.install 是函数类型,则回调这个install函数
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') { //如果传入的plugin本身是函数类型,直接回调plugin函数本身
plugin.apply(null, args)
}
installedPlugins.push(plugin) //installedPlugins 缓存传入的plugin
return this
}
}
2.1 源码所在文件位置
src/core/global-api/use.js
3 后续
本文简单的记录了学习vue源码的过程中,关于插件相关源码的解读。文章中如果有任何的错误,欢迎拍砖!
网友评论