Vue plugin
1. Overview
Simply put, plug-ins refer to enhancements or supplements to Vue's functions.
For example, you can call a method in each single page component, or share a variable, or execute a piece of code before a method, etc.
2. How to use
The overall process should be:
[Declare plug-in] —— [Writing plug-in] —— [Register plug-in] —— [Use plug-in]
Write plug-ins and declare plug-ins are synchronized, and then register them in Vue objects (don't worry about repeated registrations), and finally use the written plug-ins when writing Vue components.
Declare plugin
First write a js file, which is a plug-in file. The basic contents are as follows:
/* illustrate: * Plugin file: * Author: Wang Dong QQ: 20004604 * */ export default { install: function (Vue, options) { // The added content is written in this function } };
The first parameter of install Vue represents an instance of Vue, and the second parameter represents some setting options.
Vue instances are easy to understand, they are Vue objects.
The options setting option means that when calling this plug-in, an object can be passed.
For example, this object has a property float, and when writing a method/variable of the plugin, I need to output a number and then write an if judgment statement.
If true, output a floating point number;
If false or undefined (that is, no arguments are passed), the output is an integer.
How to add it in detail, let’s talk about it later.
Register a plug-in
If you have used Vue-router, it is easy to understand. After importing it through import, then register the plug-in through (plugin name);
For example, we usually introduce various things in it, and the root instance of the component is also here.
// import Vue from 'vue' import App from './' //The key is these two linesimport service from './' (service) new Vue({ el: '#app', render: (h) => h(App) })
As the comments in the code say, the key is to import the service file through import, and then before creating the root component, let the Vue object register the plug-in service through the use method.
With such two simple steps, you can use the plug-in.
3. Write plug-ins and use plug-ins
According to the official documentation, there are four ways to write plug-ins. First, give the official code:
//The following contents are added to the install function above // 1. Add global methods or properties = function () { // Logic...} // 2. Add global resources('my-directive', { bind (el, binding, vnode, oldVnode) { // Logic... } ... }) // 3. Inject component({ created: function () { // Logic... } ... }) // 4. Add an instance method.$myMethod = function (options) { // Logic...}
First give the most commonly used methods: [4. Add an instance method] to write and use methods
3.1 [Add instance method or attribute]
1. Core idea:
Add methods and properties through prototype.
2. Write:
//Double the output number, if it is not a number or cannot be converted implicitly into a number, then output null = function (val) { if (typeof val === 'number') { return val * 2; } else if (!isNaN(Number(val))) { return Number(val) * 2; } else { return null } }
3. Use:
Suppose there is a component like this:
<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 () { //The method here is the method in the component written above = (); } } } </script>
We can double the value of num in every click by clicking the button button.
4. If the attributes are added:
For example:
= 1;
What will happen?
1. Whether it is [pass type by value] or [pass type by reference], the variable will not be shared by different components. To be more precise, if there are two components A and B. The number value in component A changes, and the number value in component B will not change accordingly. Therefore, don’t think about referring to such a variable, and then modifying the value in A, and the B will also change automatically;
2. When the component does not have this property, when called, the value obtained through the plug-in is displayed;
When there is this property in the component, when called, the value of the property in the component is displayed;
From this, the same is true for functions. Functions with the same name in the component always overwrite the functions provided by the plug-in.
In other words, when the plug-in provides a property, if there is no property in the component, use the properties of the plug-in; if there is a component, use the component's own.
3.2 [Add global methods or attributes]
1. Core idea:
It is to add a property to the Vue object.
First contact is easy to get confused 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, it is called in the component through ()
Added through 3.2, it is called outside, through Vue instances such as ()
2. Write:
// Where to refer to = function () { alert("123") }
3. Use:
//Note that you can import Vue objects first to use()
When using it, the corresponding method will be executed, for example, here is the alert pop-up window
4. Others:
Don't ask me what happens if the attribute of Vue itself has the same name as the one I have, I haven't tried =.=
3.3【Inject component】
1. Core idea:
Just like when writing Vue components, the method names remain consistent and will be executed before executing the corresponding method names of the components.
2. Write:
For example:
({ created: function () { ("Component starts loading") } })
The code here will then be executed before the created execution of each component (including the root component).
You can write a paragraph in the created method of each component to view the test
Can be used in conjunction with [Instance Attributes] to debug or control certain functions
// Inject component({ created: function () { if () ("Component starts loading") } }) // When adding injection components, determine whether to use the criteria to notify = false;
[The method that is available to inject to non-Vue instances itself]:
If it is written to a method, for example, the methods attribute, for example, the following injection:
({ methods: { test: function () { ("mixin test"); } } })
Then, if there is a test method in the component itself, it will not execute the test method of the plug-in first, and then execute the test method of the component.
Instead, only one of them is executed, and the same-named method of the component itself is performed first. This needs attention
3. Use:
There is no need to call manually, and it will be automatically called when executing the corresponding method (and first call the plug-in, then the component itself)
4. Others:
1. If multiple plugins inject a method at the same time (for example, created, then the method that is injected first will be executed, then the injected sequence will be executed, and finally the component itself will be executed)
2. Note that methods like the methods attribute are not executed after component injection, but only one is executed, and the component itself is executed first.
3.4 [Add global resources]
1. Core idea:
The addition method is similar to the normal addition method, or even almost the same.
You can add [custom directive], [filter], [transition, etc.], here you take [filter] as an example
2. Write:
For example:
//Time formatting filter, the input content is number or Date object, the output is YYYY-MM-DD HH-MM-SS('formatTime', function (value) { = function (fmt) { //author: meizz var o = { "M+": () + 1, //month "d+": (), //day "h+": (), //Hour "m+": (), //point "s+": (), //Second "q+": ((() + 3) / 3), //Quarterly "S": () //millisecond }; if (/(y+)/.test(fmt)) fmt = (RegExp.$1, (() + "").substr(4 - RegExp.$)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = (RegExp.$1, (RegExp.$ == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } return new Date(value).Format("yyyy-MM-dd hh:mm:ss"); })
3. Use:
Just use it the same as normal use, so easy. For example:
{{num|formatTime}}
4. Others:
You can use this to find various interesting functions, write them as plug-ins, and then import them where you need them. It's super convenient!
4. Sample demo
A sample demo with simple functions is included for reference
/* illustrate: * Plugin demo for learning * This page is used to provide various processing services * Author: Wang Dong QQ: 20004604 * */ export default { install: function (Vue, options) { // 1. Add global methods or properties // No // 2. Add global resources // Time formatting filter, input content is number or Date object, output is YYYY-MM-DD HH-MM-SS ('formatTime', function (value) { = function (fmt) { //author: meizz var o = { "M+": () + 1, //month "d+": (), //day "h+": (), //Hour "m+": (), //point "s+": (), //Second "q+": ((() + 3) / 3), //Quarterly "S": () //millisecond }; if (/(y+)/.test(fmt)) fmt = (RegExp.$1, (() + "").substr(4 - RegExp.$)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = (RegExp.$1, (RegExp.$ == 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 global resources // When adding an injected component, whether to use the judgment condition to notify is also the component instance attribute = true; // 3. Inject component // Inject components, prompt before plug-in loading starts ({ created: function () { if () ("Component starts loading") }, methods: { test: function () { ("mixin test"); } } }) // 4. Add an instance method // Return the number twice the input number. If it is not a number or cannot be converted implicitly to a number, output null // Component instance method = 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, integrate instance methods into $service to avoid naming conflicts .$service = { //Telectronic number legality check 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 (tel) } } } };
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.