본문 바로가기
Web/JavaScript

[vue3] Plugins

by llHoYall 2021. 6. 25.

Vue3 has a plugin feature.

Let's learn about this.

Create a Project

Create a project for a plugin example.

2021.06.02 - [Web/JavaScript] - [Vue3] Getting Started with Vue3 + TypeScript + TailwindCSS

Creating Plugins

Let's create a plugin file.

 

plugins/vending.ts

import { Plugin } from "vue";

export const vendingPlugin: Plugin = {
  install(app, options?) {
    app.config.globalProperties.$pick = (key: number) => {
      return options[key];
    };
    app.provide("vending", options);
  },
};

This plugin gets an object when it is installed.

And it returns the value corresponding to the key when we use this.

This plugin will be served as the name that we defined.

Installing Plugins

Now, let's install this plugin before using it.

 

main.ts

import { vendingPlugin } from "./plugins/vending";

const vendingMachine = {
  1: "apple",
  2: "banana",
  3: "cherry",
};

createApp(App)
  .use(vendingPlugin, vendingMachine)
  .mount("#app");

First, I defined the object.

Next, I installed the plugin with this object using use method.

Using Plugins

Finally, we will use this plugin!

 

components/plugin.vue

<template>
  <div class="p-4 flex flex-col justify-start items-center">
    <h2 class="mt-8 mb-2 text-xl font-medium text-green-600">Plugin</h2>
    <div>{{ $pick(1) }}</div>
    <div>{{ $pick(2) }}</div>
    <div>{{ $pick(3) }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Plugin",
  inject: ["vending"],
});
</script>

If we want to use plugins, we should inject them with their name.

Then, we can use that plugin!!

Use the method with the parameters that we defined.

 

Now, it is the rendering time.

 

App.vue

<template>
  <div class="my-4 flex justify-center items-center">
    <Plugin />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import Plugin from "./components/plugin.vue";

export default defineComponent({
  name: "App",
  components: {
    Plugin,
  },
});
</script>

Conclusion

Now we can create plugins and use them.

'Web > JavaScript' 카테고리의 다른 글

[Vue3] Mixins  (0) 2021.06.26
[Vue3] Composition API  (0) 2021.06.25
[Vue3] Custom Directives  (0) 2021.06.24
[Vue3] Send Data from Ancestor Component using Provide and Inject  (0) 2021.06.20
[Vue3] Slot (v-slot) Usage  (0) 2021.06.20

댓글