Vue plug in to write with detailed explanation (with demo)

  • 2021-08-05 08:29:29
  • OfStack

Vue plug-in

1. Overview

Simply put, plug-ins refer to enhancements or supplements to the functions of Vue.

For example, in every single-page component, you can call a method, share a variable, or execute a piece of code before a method, etc.

2. How to use it

The overall process should be:

"Declare plug-ins"-"Write plug-ins"-"Register plug-ins"-"Use plug-ins"

Writing plug-ins and declaring plug-ins are synchronized, then registered in an Vue object (without fear of repeated registrations), and finally using the written plug-ins when writing Vue components

Declare plug-ins

First write an js file, this js file is the plug-in file, the basic contents are as follows:


/*   Description: 
 *   Plug-in file: service.js
 *   Author: Wang Dong   QQ : 20004604
 * */
export default {
  install: function (Vue, options) {
    //  The added content is written in this function 
  }
};

The first parameter Vue of install represents an instance of Vue, and the second parameter represents one set of options.

The Vue instance is easy to understand, that is, the Vue object.

The options setting option means that when calling this plug-in, you can pass 1 object.

For example, this object has a property float, and then when I write a method/variable of the plug-in, I need to output a number, and then write an if judgment statement.

If options. float is true, output floating point number;

If it is false or undefined (that is, no parameter is passed), the output is an integer.

How to add it, we'll talk about it later.

Register plug-ins

If you have used Vue-router, it is easy to understand. After being introduced through import, the plug-in is registered through Vue. use (plug-in name);

For example, we usually introduce various things in main. js, and the root instance of the component is also here


//main.js
import Vue from 'vue'
import App from './App.vue'

// The point is that these two lines 
import service from './service.js'
Vue.use(service)

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

As the code notes, the key is to import the service file through import, and then have the Vue object register the plug-in service through the use method before creating the root component.

With this simple two steps, you can use the plug-in.

3. Write plug-ins and use plug-ins

According to the official document, there are four ways to write plug-ins. First, give the official code:


// The following contents are all added to it install Inside the function of 

// 1.  Add a global method or property 
Vue.myGlobalMethod = function () {
  //  Logic ...
}
// 2.  Add a global resource 
Vue.directive('my-directive', {
  bind (el, binding, vnode, oldVnode) {
    //  Logic ...
  }
  ...
})
// 3.  Injection component 
Vue.mixin({
  created: function () {
    //  Logic ...
  }
  ...
})
// 4.  Add an instance method 
Vue.prototype.$myMethod = function (options) {
  //  Logic ...
}

First, give the most commonly used: "4. Add instance method" and how to write and use it

3.1 "Add Instance Method or Property"

1. Core ideas:

Use prototype to add methods and properties.

2. Write:


// Doubles the number output, and if it is not a number or cannot be implicitly converted to a number, outputs null
Vue.prototype.doubleNumber = function (val) {
  if (typeof val === 'number') {
    return val * 2;
  } else if (!isNaN(Number(val))) {
    return Number(val) * 2;
  } else {
    return null
  }
}

3. Use:

Suppose you have one component:


<template>
  <div>
    {{num}}
    <button @click="double"> Click to double the number on the left </button>
  </div>
</template>
<script>
  export default{
    data(){
      return {
        num: 1
      }
    },
    methods: {
      double: function () {
        // Here's this.doubleNumber() Method is the method in the component written above 
        this.num = this.doubleNumber(this.num);
      }
    }
  }
</script>

We can double the value of num with each click by clicking the button button.

4. If you add attributes:

For example:


Vue.prototype.number = 1;

What will happen?

1. Whether it is "passing type by value" or "passing type by reference", this variable will not be shared by different components. More precisely, if there are two components, A and B. The number value in the A component changes, and the number value in the B component does not change accordingly. So don't think about referencing such a variable, and then modify the value in A, and B will automatically change;

2. When there is no attribute in the component, the value obtained through the plug-in is displayed when calling;

When there is this attribute in the component, the value of this attribute in the component is displayed when calling;

Thus, the same is true of functions. Functions with the same name in components always override functions provided by plug-ins.

That is to say, when the plug-in provides an attribute, if there is no such attribute in the component, the attribute of the plug-in will be used; If the component has it, use the component's own.

3.2 "Add a global method or property"

1. Core ideas:

Is to add a property to the Vue object.

Initial contact is easy to confuse with 3.1 above. In fact, 3.1 is for use in components, while 3.2 is for use in Vue objects.

For example, if you add a method test (), then:

Added through 3.1, is in the component, called through this. test ()

Added through 3.2, is outside, called through an Vue instance, such as Vue. test ()

2. Write:


// Where do you put it? Refer to it 
Vue.test = function () {
  alert("123")
}

3. Use:


// Pay attention to importing first Vue Object to use the 
Vue.test()

When used, the corresponding method will be executed, for example, this is the alert pop-up window

4. Others:

Don't ask me what happens if I have the same name as Vue itself, I haven't tried =. =

3.3 "Injection Components"

1. Core ideas:

Just like when writing an Vue component, the method name remains 1, which executes before executing the corresponding method name of the component.

2. Write:

For example:


Vue.mixin({
  created: function () {
    console.log(" Component starts loading ")
  }
})

The code here is then executed before created executes for each component (including the root component).

You can write a segment of console. log in the created method of each component to view the test

It can be used in conjunction with "instance properties" to debug or control certain functions


//  Injection component 
Vue.mixin({
  created: function () {
    if (this.NOTICE)
      console.log(" Component starts loading ")
  }
})
//  When adding an injection component, use the console.log To notify the judgment conditions 
Vue.prototype.NOTICE = false;

"Injection of intrinsic methods into non-Vue instances":

If it is written to a method such as methods property, such as the following injection:


//main.js
import Vue from 'vue'
import App from './App.vue'

// The point is that these two lines 
import service from './service.js'
Vue.use(service)

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

0

Then, if there is an test method in the component itself, the test method of the plug-in will not be executed first, and then the test method of the component will be executed.

Instead, only one of them is executed, and the method with the same name of the component itself is preferred. This needs attention

3. Use:

It does not need to be called manually, but will be called automatically when executing the corresponding method (and call the plug-in first, then the component itself)

4. Others:

1. If multiple plug-ins inject one method at the same time (for example, created, the method injected first will be executed, then the injected method will be executed in turn, and finally the component itself will be executed)

2. Note that methods like those under the methods property do not execute each after component injection, but only one, and take precedence over the component itself.

3.4 "Add Global Resources"

1. Core ideas:

The addition method is similar to the normal addition method, even almost one.

You can add "custom instructions", "filters", "transitions, etc." Take "filters" as an example here

2. Write:

For example:


//main.js
import Vue from 'vue'
import App from './App.vue'

// The point is that these two lines 
import service from './service.js'
Vue.use(service)

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

1

3. Use:

And normal use of a sample, so easy. For example:


//main.js
import Vue from 'vue'
import App from './App.vue'

// The point is that these two lines 
import service from './service.js'
Vue.use(service)

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

2

4. Others:

Can use this to find a variety of interesting functions, as a plug-in to write well, and then the need to import the place on the line, super convenient!

4. Example demo

Attached is an example demo with simple functions for reference


/*  Description: 
 *  Plug-ins demo For learning and use 
 *  This page is used to provide various processing services 
 *  Author: Wang Dong   QQ : 20004604
 * */
export default {
  install: function (Vue, options) {
    // 1.  Add a global method or property 
    //  Slightly 

    // 2.  Add a global resource 
    //  Time formatting filter, the input content is number Or Date Object, the output is YYYY-MM-DD HH-MM-SS
    Vue.filter('formatTime', function (value) {
      Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
          "M+": this.getMonth() + 1, // Month 
          "d+": this.getDate(), // Day 
          "h+": this.getHours(), // Hours 
          "m+": this.getMinutes(), // Points 
          "s+": this.getSeconds(), // Seconds 
          "q+": Math.floor((this.getMonth() + 3) / 3), // Quarterly 
          "S": this.getMilliseconds() // Milliseconds 
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
      }
      return new Date(value).Format("yyyy-MM-dd hh:mm:ss");
    })

    // 2.  Add a global resource 
    //  When adding an injection component, use the console.log To notify the judgment condition, which is also the component instance property 
    Vue.prototype.NOTICE = true;


    // 3.  Injection component 
    //  Inject components, prompt before plug-in loading begins 
    Vue.mixin({
      created: function () {
        if (this.NOTICE)
          console.log(" Component starts loading ")
      },
      methods: {
        test: function () {
          console.log("mixin test");
        }
      }
    })


    // 4.  Add an instance method 
    //  The number returned is twice the number entered. If it is not a number or cannot be implicitly converted to a number, the output null
    //  Component instance method 
    Vue.prototype.doubleNumber = function (val) {
      if (typeof val === 'number') {
        return val * 2;
      } else if (!isNaN(Number(val))) {
        return Number(val) * 2;
      } else {
        return null
      }
    }

    // 4.  Add an instance method 
    //  Service group, integrating instance methods into $service Avoid naming conflicts in 
    Vue.prototype.$service = {
      // Check the legality of telephone number 
      telNumberCheck: function (tel) {
        var pattern = /(^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$)|(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        return pattern.test(tel)
      }
    }
  }
};


Related articles: