Shadeed translator: Front-end small wisdom source: Learnvue

Have a dream, have dry goods, wechat search [big move world] pay attention to this in the wee hours of the morning is still brushing the dishes of the wisdom.

In this paper, making github.com/qq449245884… Has been included, there are a line of big factory interview complete test points, information and my series of articles.

Plug-ins are a great way to add reusable functionality to Vue applications. With a large number of existing plug-ins for components, routing, and so on, Vue’s ecosystem provides solutions for many common use cases.

Some common plug-ins are Vue-Router, Vue Custom – Element, and Vue-touch.

However, there will always be times when no plugin will meet our needs and we will need to write our own plugin to meet the tastes of the product.

In this tutorial, learn how to build your own Vue 3 plug-in.

What can we do with the Vue plug-in?

Simply put, the Vue plug-in allows us to extract any type of functionality into its own contained code, which can be reused across different projects.

Typically, they are used to add global level functionality to a Vue application. Here are some of the most common uses of plug-ins, according to the Vue documentation.

  • Adding global Components
  • Adds a global directive, transition, or its resources
  • Add component options using global mixins (e.gvue-router)
  • Add the addition attribute to the Vue instance (viaapp.config.globalproperties)

Let’s start by creating our first plug-in.

Create our Vue 3 plug-in

In this tutorial, we will make a plug-in that adds UI elements and styles that allow us to add to our application.

We create a file called myplugin.js and create an export Default with the install method in it. This method takes two arguments:

  • app– by the VuecreateAppThe generatedappobject
  • options– Options passed in by the user
// MyFirstPlugin.js

export default {
    install: (app, options) => {
      // TODO
    }
}
Copy the code

Then, to insert the plug-in into the Vue application, go to the main.js file and use app.use().

// main.js import { createApp } from 'vue' import App from './App.vue' import MyFirstPlugin from './plugin' const app = CreateApp (App) app.use(MyFirstPlugin, /* can pass options as the second argument */) app.mount('# App ')Copy the code

If so, we will do the preliminary work.

Add global components from the Vue plug-in

An important use of Vue plug-ins is to add global components that can be used anywhere in a Vue project, rather than having to be imported every time.

Using the app parameter, we can declare global components using the App.componentsyntax.

By using App.ponent, we can use a single-file component or declare our component directly in a JS file.

Suppose we want to create a title component (myheader.vue)– it contains information for an article.

<template>
    <div>
        <h1 class="header-title">   
            <slot name="title" />
        </h1>
        <h2 class="title-author">
            <slot name="author" />
        </h2>
    </div>
</template>
Copy the code

Go back to myFirstPlugin.js and add it to our plug-in.

// MyFirstPlugin.js import MyHeader from './components/MyHeader.vue' export default { install: (app, options) = > {/ * declare global components * / app.com ponent (' my - the header, MyHeader)}}Copy the code

Now, we can use MyHeader anywhere because it is registered globally.

For example, in app.vue. You don’t need to import it, just add it to the template.

<template>
  <my-header>
    <template #title> 
      Building Your Own Vue 3 Plugin - <i> A Full Guide </i>
    </template>
    <template #author> 
      Matt Maribojoc
    </template>
  </my-header>
</template>
Copy the code

Running result:

We can also add styles to these components

If we add any non-scoped styles to the component, set them directly within the component.

For example, if we wanted to change the font size and background color of the entire project, we could do so in the MyHeader component.

<template> <div> <h1 class="header-title"> <slot name="title" /> </h1> <h2 class="title-author"> <slot name="author" /> < span style> < span style = "font-size: 1.2em; background: #fafafa; } </style>Copy the code

After the operation:

Add global directives using the Vue plug-in

One of my favorite things about using Vue is being able to create my own instructions.

Directives are one way that Vue allows developers to edit the DOM directly. For example, v-if, V-show, v-bind, and so on.

With plugins, we can easily create directives using app.directive and use them in multiple projects.

In short, we want to take an instruction parameter that determines the font size of an element, and then change the style of that element (via EL) to use the appropriate size.

// MyFirstPlugin.js export default { install: (app, options) => { app.component('my-header', MyHeader) app.directive("font-size", (el, binding, vnode) => { var size = 16; switch (binding.arg) { case "small": size = 12; break; case "large": size = 24; break; default: size = 18; break; } el.style.fontSize = size + "px"; }}})Copy the code

Then, inside app.vue or any component, because it is globally available, we can use the directive like this.

<template>
  <p v-font-size:small>Small</p>
  <p v-font-size:medium>Medium</p>
  <p v-font-size:large>Large</p>
  
  <my-header>
    <template #title> 
      Building Your Own Vue 3 Plugin - <i> A Full Guide </i>
    </template>
    <template #author> 
      Matt Maribojoc
    </template>
  </my-header>
</template>
Copy the code

After the operation:

Provide customization using plug-in options

Adding options to plug-ins is a great way to make them more flexible for different use situations.

Suppose we want the developer to be able to control the exact size of the small, medium, and large parameters.

Going back to main.js, we can add a second argument to app.use:

// main.js

app.use(MyFirstPlugin, {
   fontSize: {
       small: 12,
       medium: 24,
       large: 36
   }
})
Copy the code

Then, back in our plug-in, instead of hard-coding our font size, we can use the Options object to extract whatever was passed to the plug-in.

// MyFirstPlugin.js
app.directive("font-size".(el, binding, vnode) = > {
  var size = 16;
  switch (binding.arg) {
    case "small":
      size = options.fontSize.small;
      break;
    case "large":
      size = options.fontSize.large;
      break;
    default:
      size = options.fontSize.medium;
      break;
  }
  el.style.fontSize = size + "px";
});

Copy the code

After the operation:

Use Mixins to add methods, data, and other component options

A common way for plug-ins to add reusable functionality to a Vue application is to use Vue Mixins. Mixins are a way to add component options to a Vue component.

We can add any component options, such as lifecycle hooks, data, and methods, which will be combined with the component’s options if a component uses the mixin.

It is important to understand how to combine these options. For example, the mixin lifecycle hook will be called before the component hook, and the component data will take precedence over the mixin data if there is a naming conflict.

We can create a global mixin using the app.mixin method.

For example, we want to add a create hook that simply prints a log statement to our console, and we want to give a data property that gives us an external URL that we can use to change the href property of the link throughout the application.

// MyFirstPlugin.js
export default {
    install: (app, options) => {
        app.mixin({
            data() {
                return {
                    featuredLink: 'https://learnvue.co'
                }
            },
            created() {
                console.log("Printing from created.")
            },
        })
    }
}
Copy the code

In any component we use, the Created hook will run, and we can access the featuredLink property. Two prints – one for app.vue and one for myheader.vue

Use Provide and Inject in plug-ins

A powerful way to give specific components access to different properties and methods is to use the provide and Inject patterns in Vue.

This allows our plug-in to “provide” an attribute or method, and allows any component to “inject” the value.

As an example, let’s create the logout method. We don’t need this method to be available to every component, but we’d like to create just one logout method to make it easier to change in the future.

Inside our plug-in, we declare our method and call app.provide to provide it to the rest of our application.

// MyFirstPlugin.js

import { provide } from 'vue'

export default {
    install: (app, options) => {
        const logout = () => {
            console.log('Logout is being called')
        }

        app.provide('logout', logout)
    }
}
Copy the code

Then, in any component, we can inject the method and create a button that calls the logout method of the logout session.

<template>
  <button @click="logout"> Logout </button>
  <p v-font-size:small>Small</p>
  <p v-font-size:medium>Medium</p>
  <p v-font-size:large>Large</p>
  <a :href="featuredLink"> Featured Link </a>
  <my-header>
    <template #title> 
      Building Your Own Vue 3 Plugin - <i> A Full Guide </i>
    </template>
    <template #author> 
      Matt Maribojoc
    </template>
  </my-header>
</template>

<script setup>
import { inject } from 'vue'
const logout = inject('logout')
</script>
Copy the code

When we run the logout button, we can see that the logout contents are printed out every time we click the logout button.

conclusion

The possibilities for designing your own Vue 3 plugin are endless. I hope you found this helpful.

~ over, I am small wisdom, sorting out this article, is sick, ready to go to the club to relax the young model.

The possible bugs after the deployment of code can not be known in real time, in order to solve these bugs, spent a lot of time log debugging, here by the way to recommend you a good BUG monitoring toolFundebug.

Original text: learue co / 2021/06 / bui…

communication

Have a dream, have dry goods, wechat search [big move world] pay attention to this in the wee hours of the morning is still brushing the dishes of the wisdom.

In this paper, making github.com/qq449245884… Has been included, there are a line of big factory interview complete test points, information and my series of articles.