The difference between Vue.use and Vue.prototype.xxx

Both Vue.use and Vue.prototype can introduce plug-ins, both of which mount the plug-in to an instance of Vue, so that we can use the plug-in globally.

1、Vue.use()

Its parameter is {object | Function }. If the parameter is an object, the install method must be provided. If the parameter is a function, the parameter will be used as the install method. When the install method is called, Vue will be passed in as a parameter. Vue.use will automatically prevent the same plug-in from being imported multiple times, and the plug-in will only be installed once.

Create a plugin.js file

let plug1 = {
    
    
	//第一个参数是Vue 构造器,第二个可选参数
	install(Vue,options){
    
    
		Vue.prototype.$fn1 = function(){
    
    
			console.log('这是插件1里面的方法');
		}
	}
}
function plug2(Vue,options){
    
    
	Vue.prototype.$fn2 = function(){
    
    
		console.log('这是插件2里面的方法');
	}
}

export {
    
     plug1, plug2 }

Introduce plugin.js in main.js

import Vue from 'vue';
import App from './App.vue';
import {
    
     plug1, plug2 } from './plugin';

Vue.use(plug1);
Vue.use(plug2);

new Vue({
    
    
	el:'#app',
	render: h => h(App)
})

Then use it in any page

mounted(){
    
    
 	this.$fn1(); //这是插件1里面的方法
 	this.$fn2(); //这是插件2里面的方法
},

In the above case, an object is mounted on a Vue instance through Vue.use. You can use this to call the methods defined in plug1 and plug2 directly on other pages.

Note: The Vue.use method must be called before new Vue().

2 、 Vue.portotype.xxx

You may use data/utilities in many components, but you don't want to pollute the global scope. In this case, you can make them available in every instance of Vue by defining them on the prototype.

export function plug2(){
    
    
	console.log('这是插件2里面的方法');
}

Introduced in main.js

import Vue from 'vue';
import App from './App.vue';
import*as Plugin from './plugin';

Vue.prototype.$Plugin  = Plugin;

new Vue({
    
    
	el:'#app',
	render: h => h(App)
})

If used in the page

 this.$Plugin.plug2()
 //这是插件2里面的方法

In this way, the plug2 method can be used globally, even before the instance is created.

Summary: Use Vue.use() to import when using plugins written specifically for vue, and use Vue.prototype.xxx to import others.

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/112240753