今天打开Vue项目中main.js文件中,发现引入文件使用了两种方式。html
import Vue from 'vue' import App from './App.vue' import router from './router' // 引入echarts import echarts from 'echarts' import 'echarts/map/js/china.js'; Vue.prototype.$echarts = echarts // 将自动注册全部组件为全局组件 import dataV from '@jiaminghi/data-view' Vue.use(dataV)
Vue.use和Vue.prototype这两种方式引入包。那这两种方式有什么区别,既然困惑,那就本着刨根问底的心态,去了解下这两种方式的不一样。vue
1 Vue.use( plugin )markdown
咱们先看下官方的解释,echarts
参数:{Object | Function} pluginide
用法:安装 Vue.js 插件。若是插件是一个对象,必须提供 install 方法。若是插件是一个函数,它会被做为 install 方法。install 方法调用时,会将 Vue 做为参数传入。函数
该方法须要在调用 new Vue() 以前被调用。测试
当 install 方法被同一个插件屡次调用,插件将只会被安装一次。ui
仍是看代码比较直接,新建plugin文件夹,文件夹下新建plugin.jsthis
var install = function(Vue) { Object.defineProperties(Vue.prototype, { $Plugin: { value: function() { console.log('I am a plugin') } } }) } module.exports = install
main.js导入prototype
// 测试插件 import Plugin from "./plugin/plugin" Vue.use(Plugin)
使用插件
this.$Plugin()
2 Vue.prototype
这种就比较好理解了,好比咱们有个方法,
export const Plugin1 = (parameter1) => { console.log(parameter1) }
全局都要使用,全局导入。
import { Plugin1 } from "./plugin/plugin" Vue.prototype.Plugin1 = Plugin1
须要的地方调用
this.Plugin1("111")
这么一对比,区别就很明显了,什么状况下使用Vue.use,什么状况下使用Vue.prototype。
针对Vue编写的插件用Vue.use导入
编写插件能够参考官方文档: