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

MySQL 8.0.18 uses clone plugin to rebuild MGR implementation

Assume that a node in the three-node MGR is abnor...

SQL merge operation of query results of tables with different columns

To query two different tables, you need to merge ...

This article will show you the principle of MySQL master-slave synchronization

Table of contents Brief Analysis of MySQL Master-...

How to install MySQL and Redis in Docker

This article is based on the CentOS 7.3 system en...

Pure CSS to implement iOS style open and close selection box function

1 Effect Demo address: https://www.albertyy.com/2...

innodb_flush_method value method (example explanation)

Several typical values ​​of innodb_flush_method f...

Logrotate implements Catalina.out log rotation every two hours

1. Introduction to Logrotate tool Logrotate is a ...

Will this SQL writing method really cause the index to fail?

Preface There are often some articles on the Inte...

An article to understand the advanced features of K8S

Table of contents K8S Advanced Features Advanced ...

Vue3+script setup+ts+Vite+Volar project

Table of contents Create a vue + ts project using...

How to receive binary file stream in Vue to realize PDF preview

Background Controller @RequestMapping("/getP...

How to modify the IP restriction conditions of MySQL account

Preface Recently, I encountered a requirement at ...

CentOS IP connection network implementation process diagram

1. Log in to the system and enter the directory: ...

Nginx's practical method for solving cross-domain problems

Separate the front and back ends and use nginx to...