一、vue使用插件
通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成
// myPlugin.js
export default function install (Vue) {
Vue.prototype.$msg = 'hh'
}
// 或者
export default obj = {
install (Vue) {
Vue.prototype.$msg = 'hh'
}
}
----------------------------
// main.js
import myPlugin from './myPlugin'
Vue.use(myPlugin) // 作用:调用myPlugin中install方法
new Vue(option)
二、Vue.use源码
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
// 防止重复注册插件
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
var args = toArray(arguments, 1);
// 这里的this是Vue构造函数,把它放在参数的第一个位置,这就是install第一个参数是Vue的原因
args.unshift(this);
//如果插件中有install方法就执行插件的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
};
三、插件的作用
插件通常用来为 Vue 添加全局功能
1、添加全局资源:指令/过滤器/过渡等。如 vue-touch
2、通过全局混入来添加一些组件选项。如 vue-router
3、添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
4、一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
1360

被折叠的 条评论
为什么被折叠?



