Questions about Vue.prototype and vue.use ()

  javascript

Vue novice, often seen in main.js
Vue.prototype.$xxx = xxx;

clipboard.png

And use vue.use ()

clipboard.png

clipboard.png
api.js

clipboard.png

In the process of learning to use, I have implemented data call
Want to know the difference between the two

First of all, no matter which method you use, the final calling method is

vm.api()

In other words, both methods are implemented on the principle ofVue.prototypeA method was added to the. So the conclusion is “there is no difference”.

Let’s talk about it againVue.use()What did you do?

We know that,Vue.use()Can let us install a custom Vue plug-in. To do this, we need to declare an install function

//Create a simple plug-in say.js
 var install = function(Vue) {
 If (installed.installed) return//if already registered, skip
 install.installed = true
 
 Object.defineProperties(Vue.prototype, {
 $say: {
 value: function() {console.log('I am a plugin')}
 bracket
 })
 bracket
 module.exports = install

Then we will register this plug-in

import say from './say.js'
 import Vue from 'vue'
 
 Vue.use(say)

In this way, in each Vue instance inside we can callSayHere we go.

Let’s seeVue.useHow is it implemented inside the method

Vue.use = function (plugin) {
 if (plugin.installed) {
 return;
 bracket
 // additional parameters
 var args = toArray(arguments, 1);
 args.unshift(this);
 if (typeof plugin.install === 'function') {
 plugin.install.apply(plugin, args);
 } else {
 plugin.apply(null, args);
 bracket
 plugin.installed = true;
 return this;
 };

In fact, it is also called thisInstallIt’s just a method.