vue.use为注册全局插件所用,接收函数或者一个包含install属性的对象为参数;如果参数带有install就执行install,如果没有就直接将参数当install执行;并且第一个参数始终为vue对象,注册过的插件不会重新注册。
本教程操作环境:windows7系统、vue2.0版本、Dell G3电脑。
相关推荐:《vue.js教程》
定义
vue.use()往全局注入一个插件,供全局真接使用, 不需要单独引用
代码理解:
import Router from 'vue-router'// 入口文件全局注入vue-router, 从而可以在全局使用this.$routeVue.use(Router)
如果不使用vue.use那么需在组件中使用都得单独引入
// a.vueimport Router from 'vue-router'// b.vueimport Router from 'vue-router'
理解了其基本使用及作用,我们来看一下vue.use中都发生了什么
源码很少,所以直接摘抄了
Vue.use = function (plugin: Function | Object) {const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))if (installedPlugins.indexOf(plugin) > -1) {return this}// additional parametersconst 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)return this}
总结
vue.use()为注册全局插件所用,接收函数或者一个包含install属性的对象为参数,如果参数带有install就执行install, 如果没有就直接将参数当install执行, 第一个参数始终为vue对象, 注册过的插件不会重新注册。
以上就是vue.use中发生了什么的知识。速戳>>知识兔学习精品课!