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

Implementing a puzzle game with js

This article shares the specific code of js to im...

Web page HTML ordered list ol and unordered list ul

Lists for organizing data After learning so many ...

Vue Beginner's Guide: Creating the First Vue-cli Scaffolding Program

1. Vue--The first vue-cli program The development...

Building an image server with FastDFS under Linux

Table of contents Server Planning 1. Install syst...

Xhtml special characters collection

nbsp &#160; no-break space = non-breaking spa...

A brief discussion on JS packaging objects

Table of contents Overview definition Instance Me...

Detailed explanation of tcpdump command examples in Linux

Preface To put it simply, tcpdump is a packet ana...

How to use CSS attribute selectors to splice HTML DNA

CSS attribute selectors are amazing. They can hel...

Example test MySQL enum type

When developing a project, you will often encount...

Detailed explanation of Strict mode in JavaScript

Table of contents Introduction Using Strict mode ...

MySQL installation and configuration tutorial for Mac

This article shares the MySQL installation tutori...

Detailed explanation of new relational database features in MySQL 8.0

Preface The latest version of MySQL 8.0 is 8.0.4 ...

Comprehensive website assessment solution

<br />Sometimes you may be asked questions l...

Native JS to implement login box email prompt

This article shares a native JS implementation of...