Let’s write a Vue.js 3 Plugin with TypeScript from scratch – Part 2

After we created a plugin in part 1 we now want to install our Plugin to our Vue.js App

This article consists of two parts:

Create a Vue App

Probably you don’t need this step because you already have a Vue App running, but this is a tutorial, so let’s create a new one with Vite.

//yarn
yarn create vite my-vue-app --template vue-ts

// npm
npm init vite@latest my-vue-app -- --template vue-ts

This will create a new Vue App with Vite as a build tool. Vite also includes a very fast dev server.

Register our plugin

Download plugin

Before we can install our plugin in Vue, we have to download it

// yarn
yarn add @skuhnow/vue3-plugin-typescript

// npm
npm install @skuhnow/vue3-plugin-typescript

Install our plugin

import { createApp } from 'vue'
import App from './App.vue'
// Import the plugin
import {ColoredTextPlugin} from '@skuhnow/vue3-plugin-typescript'

createApp(App)
    // Tell Vue to install the plugin
    .use(ColoredTextPlugin, { color: 'green'})
    .mount('#app')

As you can see, the second parameter of the use method are our plugin options ({ color: 'green' }). This can be anything that we defined in our ColoredTextOptions interface

Test our plugin

If you haven’t already done it, install all dependencies and run the dev server

yarn
yarn dev

Now it’s time to test our plugin. To do so, just use our new Headline component in one of our templates

<template>
    <headline>This is a green text</headline>
</template>

You can also access the options with the global variable $coloredText

Either in your source

<script>
export default {
    created() {
        console.log(this.$coloredText);
    }
}
</script>

or in your template

<template>
    <div>
        {{ $coloredText }}
    </div>
</template>

The output will in both cases will be

{ "textColor": "green" }

Schreibe einen Kommentar