8
Author: Shadeed
Translator: Frontend Xiaozhi
Source: learnvue

If you have dreams and dry goods, search on [Moving to the World] Follow this wise brush who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Plugins are a great way to add reusable features to Vue applications. There are a large number of existing plugins for components, routing, etc., and the Vue ecosystem provides solutions for many common use cases.

Some commonly used plug-ins are vue-router , vue custom-element and vue-touch .

However, sometimes, when there is no plug-in that can meet our needs, we need to write a plug-in to meet the taste of the product.

In this tutorial, we will learn to build our own Vue 3 plugin.

What can we do with Vue plugins?

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

Generally, they are used to add global-level functionality to Vue applications. According to the Vue document , the following are some of the most common uses of plugins.

  • Add global components
  • Add global directives, transitions or their resources
  • Use global mixins to add component options (such as vue-router )
  • Add the addition attribute to the Vue instance (via app.config.globalproperties )

Next, we will talk about them one by one, first, let's create our first plug-in.

Create our Vue 3 plugin

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

We create a file named MyPlugin.js , and create a install method export default . This method has two parameters:

  • app app object generated by Vue's createApp
  • options -The option passed in by the user
// MyFirstPlugin.js

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

Then, in order to insert this plug-in into the Vue application, enter 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, /* 可以传递 options 作为第二个参数*/)

app.mount('#app')

If this is required, we will do the preliminary work.

Add global components from Vue plugin

An important use of Vue plugins is to add global components that can be used anywhere in the Vue project without having to import them every time.

Using the app parameter, we can use the app.component syntax to declare global components.

By using app.component , we can use single-file components or declare our components directly in the js file.

Suppose we want to create a title component ( MyHeader.vue )-it contains information about an article.

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

Go back to MyFirstPlugin.js and add it to our plugin.

// MyFirstPlugin.js

import MyHeader from './components/MyHeader.vue'
export default {
    install: (app, options) => {
        /* 声明全局组件 */      
        app.component('my-header', MyHeader)
    }
}

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

For example, App.vue is used in 06111c89105d3a. No need to import, 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>

operation result:

image.png

We can also add styles to these components

If we add any non-scoped styles to the component, just set it directly in the component.

For example, if we want to change the font size and background color of the entire project, we can MyHeader component.

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

<style>
    html, body, * {
        font-size: 1.2em;
        background: #fafafa;
    }
</style>

After running:

image.png

Use the Vue plugin to add global directives

My favorite thing about using Vue is the ability to create my own instructions.

Directives are a way for Vue to allow developers to directly edit the DOM. For example, v-if , v-show , v-bind and so on.

With plug-ins, we can easily use app.directive create instructions and use them in multiple projects.

In short, we want to accept an instruction parameter, determine the font size of the element, and then change the style of the element (through 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";
          })
    }
}

Then, inside App.vue or any component, because it is globally available, we can use instructions 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>

After running:

image.png

Use plugin options to provide customization

Adding options to the plug-in is a good way to make the plug-in more flexible in different use cases.

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

Back to main.js , we can add a second parameter app.use

// main.js

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

Then, back to our plug-in, we can use the options object to extract any content passed to the plug-in instead of hard-coding our font size.

// 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";
});

After running:

image.png

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

A common way for plugins to add reusable functionality to Vue applications is to use Vue mixins. Mixins are a way to add component options to Vue components.

We can add any component options, such as lifecycle hooks, data, and methods. If a component uses this mixin, these options will be merged with the component's options.

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

We can use the app.mixin method to create a global mixin .

For example, we want to add a creation hook, it just prints a log statement to our console, and wants to give a data attribute, it gives an external URL, we can use it to change the link in the entire application href attribute.

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

In any component we use, the created hook will run and we can access my featuredLink properties. Two prints-one for app.vue and one for myheader.vue

image.png

Use Provide and Inject in the plug-in

A powerful way to allow specific components to access different properties and methods is to use the provide and inject modes in Vue.

This allows our plug-in " provide" a property or method, and allows any component to "inject" a value of 06111c8910607d.

Take a look at an example, we create a logout method. We don't need this method to be available for every component, but we want to create only a logout method so that it will be easier to modify in the future.

Inside our plugin, we declare our method and call app.provide to provide it to other parts 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)
    }
}

Then, in any component, we can inject this method and create a logout method.

<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>

After running, you will see that whenever we click the button, the logout will be printed out.

Summarize

The possibilities for designing your own Vue 3 plugins are endless. Hope this article can be helpful to you.

~End, I am Xiaozhi. When I was finishing this article, I was ill and I was going to the clubhouse to relax.

possible bugs of 16111c8910615b code after deployment cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://learue.co/2021/06/building-your-own-vue-3-plugin-a-full-guide/

comminicate

If you have dreams and dry goods, search on [Daily Move to the World] Follow this brush-bowl wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68k 声望104.9k 粉丝