We use cookies to enhance your experience on the site
CodeWorlds

Plugins — Basics

In the NOVA LAB Command Center, each subsystem (navigation, communication, diagnostics) is a separate module. In Vue, such modules are Plugins — a way to add global functionality to an application.

What Is a Plugin?

A plugin is an object with an

install()
method or a plain function. It is invoked by
app.use()
:

1// Plugin as an object
2const myPlugin = {
3  install(app, options) {
4    // extend the application here
5  }
6}
7
8// Plugin as a function
9function myPlugin(app, options) {
10  // also valid
11}
12
13// Registration
14const app = createApp(App)
15app.use(myPlugin, { /* options */ })

What Can a Plugin Do?

In the

install()
method, you have access to the
app
instance and can:

1. Register Global Components

1const UIPlugin = {
2  install(app) {
3    app.component('NovaButton', {
4      template: `<button class="nova-btn"><slot /></button>`
5    })
6    app.component('NovaCard', {
7      template: `<div class="nova-card"><slot /></div>`
8    })
9  }
10}

2. Register Global Directives

1const DirectivesPlugin = {
2  install(app) {
3    app.directive('focus', {
4      mounted(el) { el.focus() }
5    })
6    app.directive('highlight', (el) => {
7      el.style.backgroundColor = '#00ff88'
8    })
9  }
10}

3. Share Data via provide/inject

1const ConfigPlugin = {
2  install(app, options) {
3    app.provide('config', {
4      apiUrl: options.apiUrl || 'https://api.novalab.mars',
5      theme: options.theme || 'dark',
6      version: '2.0.87'
7    })
8  }
9}
10
11// Usage
12app.use(ConfigPlugin, {
13  apiUrl: 'https://api.novalab.mars/v2',
14  theme: 'nova-dark'
15})

In any component:

1<script setup>
2import { inject } from 'vue'
3
4const config = inject('config')
5</script>
6
7<template>
8  <p>API: {{ config.apiUrl }}</p>
9  <p>Version: {{ config.version }}</p>
10</template>

4. Add Global Properties

1const UtilsPlugin = {
2  install(app) {
3    app.config.globalProperties.$formatDate = (date) => {
4      return new Date(date).toLocaleDateString('en-US')
5    }
6  }
7}

Plugin Options

The second parameter of

install()
is the options passed through
app.use()
:

1const LoggerPlugin = {
2  install(app, options = {}) {
3    const level = options.level || 'info'
4    const prefix = options.prefix || '[NOVA]'
5
6    app.provide('logger', {
7      info: (msg) => level !== 'error' && console.log(prefix, msg),
8      warn: (msg) => level !== 'error' && console.warn(prefix, msg),
9      error: (msg) => console.error(prefix, msg)
10    })
11  }
12}
13
14app.use(LoggerPlugin, {
15  level: 'info',
16  prefix: '[NOVA LAB]'
17})
Go to CodeWorlds