An article tells you how to write a Vue plugin

An article tells you how to write a Vue plugin

What is a plugin

In the Vue framework, if we need to add some functions we need to Vue, Vue has left me a plug-in method. We can write our own plug-in, then register the plug-in in Vue, and then use it.

Through Vue plug-ins, we can implement some functions that the Vue framework does not have, or we can use plug-ins written by others to help us implement some functions more quickly.

There are no strict requirements for the functional scope of the plug-in. According to the official examples, there are generally the following types:

1. Add global methods or attributes, such as vue-custom-element . We can add some global components as plug-ins, and then use them in any page or component. This is also how Element UI or Ant Design component libraries install components.

2. Add global resources: instructions/transitions, etc. For example: vue-touch , we can also use plug-ins to add some global custom instructions to implement our functions.

3. Add some component options via global mixin. (such as vue-router )

4. Add global instance methods by adding them to config.globalProperties . For example, we may often put the $http request on the global instance method, so that we can use it in any page or component without having to explicitly import it.

5. A library that provides its own API and provides one or more of the functions mentioned above. Such as vue-router , vuex , etc.

Writing plugins

Writing a Vue plug-in is actually very simple. A plug-in is actually an object or a function. If it is an object, the install method in the object will be called, and if it is a function, this function will be called. Whether calling the install method of an object or calling a function, they will receive two parameters: 1 is the app object generated by Vue's createApp, and 2 is the parameters passed in by the user.

Let's start with the simplest i18n function.

Generally, we put the plug-in in the plugins folder, which is easy to maintain and manage.

We create an i18n.js file

export default {
  install: (app, options) => {
    // Write plugin code}
}

For example, if we need a global function to translate the entire program, we can hang the method on the app.config.globalProperties property to expose it.

The function receives a key string which we will use to look up the converted string in the user-provided arguments object.

// plugins/i18n.js
export default {
  install: (app, options) => {
    app.config.globalProperties.$translate = key => {
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }
  }
}

It is assumed that when using the plugin, the user will pass an object containing the translated keys in the options parameter. Our $translate function will use a string such as greetings.hello so the value looked up will be Bonjour!.

For example:

greetings:
  hello: 'Bonjour!'
}

We can also use inject to provide functionality or properties, for example, we can allow the application to access the options parameter to be able to use the parameters object passed in when installing the plugin.

// plugins/i18n.js
export default {
  install: (app, options) => {
    app.config.globalProperties.$translate = key => {
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }
    app.provide('i18n', options)
  }
}

Now we can use inject[i18n] to inject it into some pages or components to access the object.

Since, Vue provides me the app object as the first argument of the plugin, all other features are available to the plugin, such as using mixins and directives. To learn more about createApp and application instances, check out the Application API documentation.

For example, below we register a new custom directive in the plugin, as well as a global mixin method:

// plugins/i18n.js
export default {
  install: (app, options) => {
    app.config.globalProperties.$translate = (key) => {
      return key.split('.')
        .reduce((o, i) => { if (o) return o[i] }, options)
    }
    app.provide('i18n', options)
    app.directive('my-directive', {
      mounted (el, binding, vnode, oldVnode) {
        // some logic ...
      }
      //...
    })
    app.mixin({
      created() {
        // some logic ...
      }
      //...
    })
  }
}

Using plugins

After we have written the plug-in above, we can use the plug-in. Using plugins in Vue is also very simple. We can add plugins to our application by using the use() method.

use() method takes two parameters. The first one is the plugin to install.

The second parameter is optional, we can pass some custom parameters to the plugin.

// main.js
import { createApp } from 'vue'
import Root from './App.vue'
import i18nPlugin from './plugins/i18n'
const app = createApp(Root)
const i18nStrings = {
  greetings:
    hi: 'Hallo!'
  }
}
app.use(i18nPlugin, i18nStrings)
app.mount('#app')

Finally, we use this plugin in the page:

<template>
  <h1>{{ $translate("greetings.hi") }}</h1>
  <div>i18n plugin example</div>
</template>

The final display:

image-20211118233316846

Summarize

Reference: https://v3.cn.vuejs.org/guide/plugins.html

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • About the problem of writing plugins for mounting DOM in vue3
  • Case analysis of writing plugins in vuex
  • How to write vue plugins using vue-cli
  • Vue shopping cart plug-in writing code
  • Detailed explanation of using webpack to package and write a vue-toast plugin
  • How to write a registration plug-in based on Vuejs and Element

<<:  Summary of web designers' experience and skills in learning web design

>>:  Html+CSS floating advertisement strip implementation

Recommend

Tutorial on deploying nginx+uwsgi in Django project under Centos8

1. Virtual environment virtualenv installation 1....

MySQL Interview Questions: How to Set Up Hash Indexes

In addition to B-Tree indexes, MySQL also provide...

MySQL 5.7.20 free installation version configuration method graphic tutorial

I have seen many relevant tutorials on the Intern...

JavaScript functional programming basics

Table of contents 1. Introduction 2. What is func...

Implementing a simple age calculator based on HTML+JS

Table of contents Preface Demonstration effect HT...

Analyzing Linux high-performance network IO and Reactor model

Table of contents 1. Introduction to basic concep...

Use JS to zoom in and out when you put the mouse on the image

Use JS to zoom in and out when the mouse is on th...

How to implement image mapping with CSS

1. Introduction Image maps allow you to designate...

Implementation of Single Div drawing techniques in CSS

You can often see articles about CSS drawing, suc...

jQuery implements simple button color change

In HTML and CSS, we want to set the color of a bu...

Nginx routing forwarding and reverse proxy location configuration implementation

Three ways to configure Nginx The first method di...

JavaScript quickly implements calendar effects

This article example shares the specific code of ...

Detailed installation tutorial of mysql-8.0.11-winx64.zip

Download the zip installation package: Download a...