In-depth understanding of Vue's plug-in mechanism and installation details

In-depth understanding of Vue's plug-in mechanism and installation details

Preface:

When we use Vue, we often use and write some custom plug-ins, and then introduce them using Vue.use . So when it comes to writing plug-ins, the install method is essential. Vue.js plugins should expose an ` install method. The first argument to this method is the Vue constructor, and the second argument is an optional options object. This is Vue official specification for Vue plugins. So what exactly is this install function, what exactly does Vue use it for internal processing, and how is it called? Today I will explain it clearly to you from the source code level.

After reading this article, you will learn:

  • What the install function can do;
  • How is install implemented internally?
  • What exactly does Vuex and Vue-Router plugin do during install?

Okay, without further ado, let’s get started! ! !

1. Processing of install in Vuex&Vue-Router

Here are two questions for you to think about. They are like digging holes. I will answer them one by one below:

  • Why can we directly use $router $store in our project to get the values ​​and some methods?
  • Why are these two plug-ins introduced using Vue.use first? Then create the instance and pass it into the Vue instance;

In fact, the principles of the two are the same. Here we use Vue-Router as an example. First, let's take a look at the specific implementation of its internal install:

class Router {
    constructor(options) {
        ...
    }
}

Router.install = function(_Vue) {

    _Vue.mixin({
        beforeCreate() {
            if (this.$options.router) {
                _Vue.prototype.$router = this.$options.router
            }
        }
    })

}

export default Router;
  • What is _Vue.mixin global mixin? This is equivalent to mixing this method into all components;
  • What is beforeCreate ? Of course, it is a life cycle of Vue, which is executed before create ;

In this case, let us make a bold judgment. Vue-Router actually uses a global mixin in the install function, and mounts this.$options.router to the Vue prototype when the beforeCreate life cycle is triggered, so that we can use this.$router to call router instance. Classmate: Wait a minute, stop! ! ! You sound very Sister Li, but what is this.$options.router and where does it come from?

Don’t worry, we have just solved the first problem, now let’s fill the second hole.

We usually use Vue-Router , and the Vue instance that defines the entry file is probably like this

// router/index.js
import VueRouter form 'vue-router';
import Vue from 'vue';

Vue.use(VueRouter);

const _router = [
    ...
]

const Router = new VueRouter(_router);

export default Router;

// main.js
import Vue from 'vue';
import router from 'router';

new Vue({
    router,
    ...
}).$mount('#app');

Combining the initial example, let’s analyze it first.

  • Vue.use() mainly calls the install method inside the plug-in and passes Vue instance as a parameter;
  • this.$options.router is used above, options usually represents configuration items;
  • In main.js, we pass the Router instance as a configuration item into the Vue instance

bite! ! ! Elements are detected, so let's make a bold guess. Vue-Router first use a global mixin in order to obtain router instance in the Vue root instance configuration item and execute mounting at the right time. Then, when the new Vue() root instance is created, router instance is injected, and then the life cycle in the global mixin is triggered. At this time, the configuration item this.$options of the root instance already contains router instance, and finally the mounting process is completed! ! ! This section of code alone is so logically rigorous and the programming ideas are so clever that it makes people call it an expert! Brothers, type the word "insider" on the public screen, hhhh.

2. Internal implementation of install in Vue

After reading the usage of the commonly used library install , I wonder if you have gained anything. After the warm-up, we can start to look at the internal implementation of install , starting with the source code.

export function initUse (Vue: GlobalAPI) {
    // Register a use method mounted on the instance Vue.use = function (plugin: Function | Object) {
        // Initialize the array of current plug-ins const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
        // If this plugin has already been registered, then do not process it if (installedPlugins.indexOf(plugin) > -1) {

            return this

        }

        ...
        
        // Here comes the point! ! !
        if (typeof plugin.install === 'function') {
        // When install is a function in the plugin, call the install method, point to the plugin, and pass a number of parameters to plugin.install.apply(plugin, args)

        } else if (typeof plugin === 'function') {
        // When the plugin itself is a function, treat it as the install method, point to the plugin, and pass a bunch of parameters into plugin.apply(null, args)

        }
        
        //Put the plugin into the plugin array installedPlugins.push(plugin)

        return this
    }
}

This part of the source code is very concise and highly readable. That is, when using, determine the plug-in type and execute install or the plug-in itself. In fact, if we elaborate on the explanation on the official website, Class plug-in should expose an install method.

Conclusion:

I wonder if you have a deeper understanding of Vue's plug-in mechanism? In fact, when developing plug-ins, we can use install to do many other things. For example, Vue-Router actually registers the global components of Router-view and Router-link in install.

This is the end of this article about in-depth understanding of Vue's plug-in mechanism and install . For more relevant in-depth understanding of Vue's plug-in mechanism and installation content, please search for previous articles on 123WORDPRESS.COM 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 npm install install a specified version operation
  • vue custom component (used by Vue.use()) is the usage of install
  • Vue Pitfalls - Installing dependent modules in the project npm install reports an error
  • Introduction to install method in Vue

<<:  Bugs encountered when using mybatis-generator with mysql8.0.3 in IDEA

>>:  In-depth explanation of MySQL stored procedures (in, out, inout)

Recommend

HTML implementation of a simple calculator with detailed ideas

Copy code The code is as follows: <!DOCTYPE ht...

How to redirect nginx directory path

If you want the path following the domain name to...

Analysis of the solution to Nginx Session sharing problem

This article mainly introduces the solution to th...

Div adaptive height automatically fills the remaining height

Scenario 1: Html: <div class="outer"...

Solution to the problem that the mysql8.0.11 client cannot log in

This article shares with you the solution to the ...

Simple writing of MYSQL stored procedures and functions

What is a stored procedure Simply put, it is a se...

mysql 5.7.17 winx64.zip installation and configuration method graphic tutorial

Preface: I reinstalled win10 and organized the fi...

Pure CSS to achieve hover image pop-out pop-up effect example code

Implementation principle The main graphics are co...

Comparison of storage engines supported by MySQL database

Table of contents Storage Engine Storage engines ...

JavaScript data structure bidirectional linked list

A singly linked list can only be traversed from t...

A detailed tutorial on how to install Jenkins on Docker for beginners

Jenkins is an open source software project. It is...

What is a MySQL tablespace?

The topic I want to share with you today is: &quo...