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导入

编写插件可以参考官方文档:

https://cn.vuejs.org/v2/guide/plugins.html#ad

posted @ 2022-05-31 18:09  青年码农  阅读(261)  评论(0编辑  收藏  举报