The principle and basic use of Vue.use() in Vue

The principle and basic use of Vue.use() in Vue

Preface

I believe that many people will use Vue.use() when using other people's components with Vue. For example: Vue.use(VueRouter), Vue.use(MintUI). But when using axios, you don’t need to use Vue.use(axios), you can use it directly. So why is this?
Because axios is not installed.

1. Understanding with examples

Create two files in the new project: plugins.js use.js:

// plugins.js
const Plugin1 = {
  install(a,b){
    console.log('Plugin1 first parameter:',a)
    console.log('Plugin1 second parameter:',b)
  }
}

function Plugin2(a,b){
  console.log('Plugin2 first parameter:',a)
  console.log('Plugin2 second parameter:',b)
}

export{Plugin1,Plugin2}
// use.js 
import Vue from 'vue'
import {Plugin1,Plugin2} from './plugins'

Vue.use(Plugin1,'parameter 1')
Vue.use(Plugin2,'parameter A')
// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './assets/plugins/use'

Vue.config.productionTip = false
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

From this we can see that the two consoles we wrote in the install method in plugin1 are printed out. The first one prints the Vue object, and the second one is the parameter we passed in.

Plugin2 does not have an install method. It is a method itself and can also print two parameters. The first is the Vue object, and the second is the parameter we passed in.
So now we have a vague guess about Vue.use~

2. Analyze the source code

toArray source code

export function toArray (list: any, start?: number): Array<any> {
  start = start || 0
  let i = list.length - start
  const ret: Array<any> = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}
import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this
  }
}

From the source code, we can find that Vue first determines whether the plug-in has been registered, does not allow repeated registration, and the received plugin parameters are limited to the Function | Object type.

There are different treatments for these two types.

First, we organize the parameters we passed into an array: const args = toArray(arguments, 1);

Then add the Vue object to the beginning of the array args.unshift(this) , where this points to the Vue object;

If the install of the plugin we pass in (the first parameter of Vue.use) is a method. That is to say, if we pass in an object that contains an install method, then we call the install method of this plugin and pass the sorted array as a parameter to the install method, plugin.install.apply(plugin, args);

If the plugin we pass in is a function, then we call the function directly and pass the sorted array as a parameter, plugin.apply(null, args);

Then add this plug-in to the array of plug-ins that have been added, indicating that it has been registered installedPlugins.push(plugin);
Finally, return the Vue object.

3. Summary

Through the above analysis, we can know that there are two ways to write plug-ins in the future.

One is to encapsulate the logic of this plug-in into an object, and finally write the business code in install to expose it to the Vue object. The advantage of doing this is that you can add arbitrary parameters to this object to make the install function more concise and more extensible.

Another way is to write all the logic into a function and expose it to Vue.

In fact, the principles of the two methods are the same, except that the second method directly treats the plug-in as an install function.

Personally, I think the first method is more reasonable.

export const Plugin = {
    install(Vue) {
        Vue.component...
        Vue.mixins...
        Vue...
        // We can also execute other functions in install, Vue will point this to our plugin console.log(this) // {install: ...,utils: ...}
        this.utils(Vue) // Execute utils function console.log(this.COUNT) // 0
    },
    utils(Vue) {
        Vue...
        console.log(Vue) // Vue
    },
    COUNT: 0    
}
// We can add parameters to this object, and Vue will only execute the install method, while other methods can be used as auxiliary functions to encapsulate the install method const test = 'test'
export function Plugin2(Vue) {
    Vue...
    console.log(test) // 'test'
    // Note that if the plugin is written as a function, Vue will only point this to null, not to this function console.log(this) // null
}
// In this way, we can only write the plug-in logic in one function, and the encapsulation is not so strong

Summarize

This concludes this article about the principles and basic usage of Vue.use() in Vue. For more relevant Vue Vue.use() principles and usage content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue custom component (used by Vue.use()) is the usage of install
  • A brief discussion on the vue.use() method from source code to usage
  • Specific usage of Vue's new toy VueUse
  • Usage of Vue.use() and installation

<<:  MySQL 8.0.22 download, installation and configuration method graphic tutorial

>>:  Analysis of HTTP interface testing process based on postman

Recommend

VMware vSAN Getting Started Summary

1. Background 1. Briefly introduce the shared sto...

Specific use of pthread_create in linux to create threads

pthread_create function Function Introduction pth...

How to change the Ali source in Ubuntu 20.04

Note that this article does not simply teach you ...

JS implements sliding up and down on the mobile terminal one screen at a time

This article shares with you the specific code of...

Nginx implements https website configuration code example

https base port 443. It is used for something cal...

JavaScript to achieve a simple page countdown

This article example shares the specific code of ...

How to publish a locally built docker image to dockerhub

Today we will introduce how to publish the local ...

Detailed explanation of four types of MySQL connections and multi-table queries

Table of contents MySQL inner join, left join, ri...

Detailed explanation of several ways to create a top-left triangle in CSS

Today we will introduce several ways to use CSS t...

View the number of files in each subfolder of a specified folder in Linux

count script #!/bin/sh numOfArgs=$# if [ $numOfAr...

How to get the current time using time(NULL) function and localtime() in Linux

time(); function Function prototype: time_t time(...

MySQL Community Server compressed package installation and configuration method

Today, because I wanted to install MySQL, I went ...

How to create and run a Django project in Ubuntu 16.04 under Python 3

Step 1: Create a Django project Open the terminal...

Web Design Teaching or Learning Program

Section Course content Hours 1 Web Design Overvie...