Vue.use和Vue.prototype的区别

今天打开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导入
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值