irpas技术客

Vue.use和Vue.prototype的区别_iu№

大大的周 2419

今天打开Vue项目中main.js文件中,发现引入文件使用了两种方式。

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这两种方式引入包。那这两种方式有什么区别,既然困惑,那就本着刨根问底的心态,去了解下这两种方式的不同。

1 Vue.use( plugin )

我们先看下官方的解释,

参数:{Object | Function} plugin 用法:安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。 该方法需要在调用 new Vue() 之前被调用。 当 install 方法被同一个插件多次调用,插件将只会被安装一次。

还是看代码比较直接,新建plugin文件夹,文件夹下新建plugin.js

var install = function(Vue) { Object.defineProperties(Vue.prototype, { $Plugin: { value: function() { console.log('I am a plugin') } } }) } module.exports = install

main.js导入

// 测试插件 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导入不是针对Vue编写的插件用Vue.prototype导入


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #import #Vue #from #vueimport #APP