Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Plugins — Podstawy

W Centrum Dowodzenia NOVA LAB każdy podsystem (nawigacja, komunikacja, diagnostyka) to oddzielny moduł. W Vue takie moduły to Plugins — sposob na dodawanie globalnej funkcjonalności do aplikacji.

Czym jest Plugin?

Plugin to obiekt z metoda

install()
lub zwykła funkcja. Jest wywoływany przez
app.use()
:

1// Plugin jako obiekt
2const myPlugin = {
3  install(app, options) {
4    // tutaj rozszerzamy aplikację
5  }
6}
7
8// Plugin jako funkcja
9function myPlugin(app, options) {
10  // również poprawne
11}
12
13// Rejestracja
14const app = createApp(App)
15app.use(myPlugin, { /* opcje */ })

Co może robić Plugin?

W metodzie

install()
masz dostęp do instancji
app
i możesz:

1. Rejestrować globalne komponenty

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. Rejestrować globalne dyrektywy

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. Udostępniać dane przez 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// Użycie
12app.use(ConfigPlugin, {
13  apiUrl: 'https://api.novalab.mars/v2',
14  theme: 'nova-dark'
15})

W dowolnym komponencie:

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>Wersja: {{ config.version }}</p>
10</template>

4. Dodawać globalne właściwości

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

Opcje pluginu

Drugi parametr

install()
to opcje przekazane przez
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})
Vai a CodeWorlds