个人理解,多多指教
- 用法
如果插件是一个对象,必须提供
install
方法。如果插件是一个函数,它会被作为 install 方法。install
方法调用时,会将 Vue 作为参数传入。
-
demo (自定义插件)
use.js
import Vue from 'vue'; //引入自定义组件 import {sortStr,loadingTemp} from './index'; Vue.use(sortStr); Vue.use(loadingTemp); 复制代码
plugin.js
const sortStr = { install(Vue) { Vue.prototype.sortStr = (str = '') => str.split('').sort().join(''); } }; function loadingTemp(Vue,arr = []) { let _temp = '<div>loading..</div>' Vue.component('Loading',{ template: _temp }) } export {sortStr,loadingTemp} 复制代码
main.js
需要引入 js
import './use.js' 复制代码
- 组件中直接使用
`<Loading></Loading>` this.sortStr('cba'); //console abc 复制代码
-
源码(注解)
Vue.use = function (plugin: Function | Object) {
//通过 indexOf 判断的是插件中是否已经存在该插件
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
//处理参数 把原有的参数转换成数组
const args = toArray(arguments, 1);
//在第一位插入this(VUE)
args.unshift(this)
if (typeof plugin.install === 'function') {
//定义了install函数
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
//本身就是一个函数
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END