Kurs Vue.js · Moduł 14: Dyrektywy i pluginy

Projekt: Dashboard API z dyrektywami i pluginami

2 min czytania ·
W tej lekcji3

To jest główny projekt modułu! Połączymy wszystko, czego się nauczyliśmy: custom directives, plugins i komunikację HTTP/API w jeden spójny system - Dashboard Centrum Dowodzenia NOVA LAB.

Architektura projektu

Nasz dashboard zawiera:

  1. Toast Plugin - powiadomienia o zdarzeniach stacji
  2. Custom Directives - v-focus, v-tooltip, v-highlight
  3. Composable useFetch - pobieranie danych z API
  4. Stany loading/error/data - obsługa błędów
  5. Akcje CRUD - dodawanie, usuwanie danych

Struktura kodu

Plugin Toast:

const ToastPlugin = {
  install(app) {
    const toasts = ref([])
    let id = 0

    app.provide('toast', {
      show(message, type = 'info') {
        const toastId = id++
        toasts.value.push({ id: toastId, message, type })
        setTimeout(() => {
          toasts.value = toasts.value.filter(t => t.id !== toastId)
        }, 3000)
      },
      success(msg) { this.show(msg, 'success') },
      error(msg) { this.show(msg, 'error') },
      list: toasts
    })
  }
}

Custom Directives:

app.directive('focus', {
  mounted(el) { el.focus() }
})

app.directive('highlight', (el, binding) => {
  el.style.border = `2px solid ${binding.value || '#00ff88'}`
})

Composable:

function useFetch(url) {
  const data = ref(null)
  const loading = ref(false)
  const error = ref(null)

  async function execute() {
    loading.value = true
    error.value = null
    try {
      const res = await fetch(url)
      data.value = await res.json()
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  execute()
  return { data, loading, error, refetch: execute }
}

Łączenie w dashboard

Dashboard wyświetla:

  • Liste misji pobraną z API
  • Formularz dodawania nowych misji
  • Toast notifications przy akcjach
  • Dyrektywy do interaktywności (focus, highlight)

Ten projekt demonstruje, jak różne części Vue (dyrektywy, pluginy, composables) współpracują w realnej aplikacji.

Kod do tej lekcji: App.vue
<script setup>
import { ref, inject } from 'vue'
import { useFetch } from './composables/useFetch.js'

const toast = inject('toast')

const vFocus = {
  mounted(el) { el.focus() }
}

const vHighlight = (el, binding) => {
  el.style.border = '2px solid ' + (binding.value || '#00ff88')
  el.style.borderRadius = '8px'
}

const { data: missions, loading, error, refetch } = useFetch(
  'https://jsonplaceholder.typicode.com/posts?_limit=8'
)

const newMission = ref('')
const sending = ref(false)

async function addMission() {
  if (!newMission.value.trim()) return
  sending.value = true

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title: newMission.value,
        body: 'Misja stacji NOVA LAB',
        userId: 1
      })
    })
    const created = await response.json()
    missions.value.unshift({ ...created, id: Date.now() })
    newMission.value = ''
    toast.success('Misja dodana pomyslnie!')
  } catch (err) {
    toast.error('Blad dodawania misji: ' + err.message)
  } finally {
    sending.value = false
  }
}

function removeMission(id) {
  missions.value = missions.value.filter(m => m.id !== id)
  toast.warning('Misja usunieta')
}
</script>

<template>
  <div class="nova-lab">
    <h1>Dashboard - Centrum Dowodzenia NOVA LAB</h1>

    <section v-highlight="'#00b4d8'" class="section">
      <h2>Nowa misja</h2>
      <form @submit.prevent="addMission" class="form">
        <input
          v-focus
          v-model="newMission"
          placeholder="Nazwa misji..."
          class="input"
          :disabled="sending"
        />
        <button type="submit" class="btn" :disabled="sending">
          {{ sending ? '...' : 'Dodaj' }}
        </button>
      </form>
    </section>

    <section v-highlight class="section">
      <div class="header-row">
        <h2>Aktywne misje</h2>
        <button @click="refetch" class="btn small">Odswiez</button>
      </div>

      <div v-if="loading" class="status loading">Ladowanie...</div>
      <div v-else-if="error" class="status error">{{ error }}</div>
      <div v-else>
        <div v-for="m in missions" :key="m.id" class="mission">
          <div>
            <strong class="mission-id">#{{ m.id }}</strong>
            <span class="mission-title">{{ m.title }}</span>
          </div>
          <button @click="removeMission(m.id)" class="btn del">X</button>
        </div>
        <p class="count">Razem: {{ missions.length }} misji</p>
      </div>
    </section>

    <div class="toast-container">
      <div
        v-for="t in toast.list.value"
        :key="t.id"
        :class="['toast', t.type]"
      >
        {{ t.message }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #c0c0c0;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; font-size: 18px; }
h2 { color: #00b4d8; font-size: 16px; margin: 0; }
.section { padding: 15px; margin-bottom: 15px; }
.form { display: flex; gap: 10px; margin-top: 10px; }
.input {
  flex: 1;
  background: rgba(0,255,136,0.05);
  border: 1px solid #00ff88;
  color: #00ff88;
  padding: 10px;
  border-radius: 6px;
  font-family: monospace;
}
.input:focus { outline: none; box-shadow: 0 0 8px rgba(0,255,136,0.3); }
.btn {
  background: rgba(0,255,136,0.15);
  color: #00ff88;
  border: 1px solid #00ff88;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-family: monospace;
}
.btn.small { font-size: 12px; padding: 4px 10px; }
.btn.del {
  color: #e74c3c; border-color: #e74c3c;
  background: rgba(231,76,60,0.15);
  padding: 4px 10px;
}
.header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.status { padding: 15px; text-align: center; }
.status.loading { color: #00b4d8; }
.status.error { color: #e74c3c; }
.mission {
  display: flex; justify-content: space-between; align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid rgba(0,180,216,0.1);
}
.mission:last-child { border-bottom: none; }
.mission-id { color: #00b4d8; margin-right: 8px; }
.mission-title { font-size: 13px; }
.count { color: #666; font-size: 12px; margin-top: 10px; text-align: right; }
.toast-container {
  position: fixed; top: 20px; right: 20px;
  display: flex; flex-direction: column; gap: 8px; z-index: 1000;
}
.toast {
  padding: 10px 18px; border-radius: 8px;
  font-family: monospace; font-size: 13px;
  animation: slideIn 0.3s ease;
}
.toast.success { background: rgba(46,204,113,0.9); color: white; }
.toast.error { background: rgba(231,76,60,0.9); color: white; }
.toast.warning { background: rgba(243,156,18,0.9); color: white; }
.toast.info { background: rgba(0,180,216,0.9); color: white; }
@keyframes slideIn {
  from { transform: translateX(100%); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

  1. Projekt do wysłaniaLink do mentora: Custom Directives, Plugins i zaawansowane wzorce
  2. WideoPodsumowanie modułu

Przydatne artykuły