Definition and use of Vue plug-ins

overview

Before studying this article, we need to figure out what is a plug-in? A plug-in is actually an extension program whose main purpose is to extend functions. Just like the plug-ins of the Idea family and the VSCode family, they are also extension programs. After installing them in the IDE, you can use the functions implemented in the plug-ins. The same is true for the plug-ins in Vue. Through plug-ins, we can extend the functions and functions of Vue components. Variables, and make the code more maintainable and extensible. Next, let's see how Vue's plugins are defined and used.

Example analysis

The definition and use of Vue plugins are very simple, the steps are as follows:

1. Define the plugin

   const myPlugin = {
    
    
        install(app,options){
    
    
            app.provide('name','walt zhong'); // 提供一个全局的变量
            console.log(app,options);
             app.mixin({
    
    
                mounted(){
    
    
                    console.log('mixin');
                }
            });
            // 对Vue底层做扩展,扩展了一个全局属性
            app.config.globalProperties.$sayHello = 'hello world'; 
        }
    }

Vue uses the install(app, options) method when defining plugins. The first parameter is the app instance of Vue, and the second parameter can be used to read the parameters we passed. In the above code, we extended a global variable and Vue's mixin block (mixin), and also extended a global attribute to the bottom layer of Vue.
Vue的mixin混入块也是一种对程序做扩展的方法,这里不多介绍,混入的方式扩展会让代码的可读性降低,并且项目越大越难维护。一般都是和插件搭配使用,因为插件的可读性和可维护性比较好

2. Using plugins

When using a plugin, we use the Vue instance app.use(plugin name, parameter), the code is as follows:

app.use(myPlugin,{
    
    name1:'walt'});

Then we can use the variable expanded in our plugin

   app.component('my-title',{
    
    
        inject:['name'],
        mounted(){
    
    
            console.log(this.$sayHello);
        },
        template: `<div>{
    
    {
    
    name}}</div>`
    });

In the above code, we defined a my-titlecomponent named, at this time we can use the inject keyword to get the name variable we defined in the plug-in, don’t we need to call the mixed syntax directly, because mixin is originally a Vue instance An attribute, so when we call app.use()the method, the related method in the mixin syntax block will be called at the right time. Our extended global attributes need to be called in a way, such as the way this.$xxxxin this examplethis.$sayHello

3. Example display

1. The input box automatically focuses

In the previous chapters, we have implemented the case of automatic focus of the input box. The automatic focus of the input box is realized by using Vue's custom instructions. Here we combine the plug-in to achieve this requirement. code show as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>输入框自动聚焦</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="root"></div>
</body>
<script>
    const myPlugin = {
    
    
        install(app,options){
    
    
            app.provide('inputName','输入框名称'); // 提供输入框的名称全局变量
            app.directive('focus',{
    
    
                mounted(el){
    
    
                    el.focus();
                }
            });
        }
    }
 const app = Vue.createApp({
    
    
        template: 
        `
         <my-focus-input  />   
        `
    });  

    app.component('my-focus-input',{
    
    
        inject:['inputName'],
        template: `<div>{
    
    {
    
    inputName}} <input v-focus/></div>`
    });

    app.use(myPlugin);

    const vm = app.mount('#root');
</script>

operation result:

2. Custom data verification

In this case, we use the plug-in and mixin syntax to implement a verification function to verify our name and age. If the age is greater than 25 years old, we output too old, otherwise the output is very young. If the length of the name is greater than 4, We output normally, otherwise the output name is too short. code show as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用插件做数据校验</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="root"></div>
</body>
<script>

    const validatorPlugin=(app,options)=>{
    
    
        app.mixin({
    
    
         created(){
    
    
            console.log('mixin ready');
            console.log(this.$options.rules);
            for(let key in this.$options.rules){
    
    
                const item = this.$options.rules[key];
                console.log(this);
                this.$watch(key,(value)=>{
    
    
                    console.log("old: "+key + " ,new: " + value);
                    const result = item.validate(value);
                    if(!result){
    
    
                        console.log(item.message);
                    }

                });
                console.log(key,item);
            }
         }
    });
  }
 const app = Vue.createApp({
    
    
    data(){
    
    
        return{
    
    
            name:'walt',age:28
        }
    },
    rules:{
    
    
        age:{
    
    
            validate:(age)=>{
    
    return age > 25},
            message:'too young'
        },
        name:{
    
    
            validate:name=> name.length>=4,
            message:'name too short'
        }
    },
        template: 
        `
        <div>name: {
    
    {
    
    name}},age:{
    
    {
    
    age}}</div>
        `
    });  

    app.use(validatorPlugin);
    const vm = app.mount('#root');
</script>

Running results:
insert image description here
# Summary
This article mainly introduces the definition and use of plug-ins. The use of plug-ins can make our code more scalable and readable. Correct use of plug-ins can help us write very elegant code. Readers are recommended to follow Implement the above two examples by hand, and deeply grasp the use of the plug-in and its beauty.

Guess you like

Origin blog.csdn.net/zxj2589/article/details/130377825