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

Renderless Components i Functional Patterns

3 min czytania ·
W tej lekcji6

W Centrum Dowodzenia NOVA LAB nie wszystkie moduły interfejsu muszą mieć wizualną reprezentację. Niektóre odpowiadają wyłącznie za logikę - to renderless components. Poznajmy zaawansowane wzorce komponentów Vue.

Czym jest Renderless Component?

Renderless component to komponent, który nie renderuje własnego HTML - zamiast tego udostępnia logikę przez slot. Cały wygląd definiuje komponent-rodzic.

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// Renderless component - logika zegara
const now = ref(new Date())
let timer = null

onMounted(() => {
  timer = setInterval(() => {
    now.value = new Date()
  }, 1000)
})

onUnmounted(() => clearInterval(timer))

defineExpose({ now })
</script>

<template>
  <slot :now="now" :formatted="now.toLocaleTimeString('pl-PL')" />
</template>

Użycie:

<template>
  <Clock v-slot="{ formatted }">
    <div class="station-clock">{{ formatted }}</div>
  </Clock>
</template>

Komponent Clock nie ma własnego HTML - przekazuje dane przez scoped slot, a rodzic decyduje o wyglądzie.

Wzorzec Renderless z logiką toggle

Popularny wzorzec - komponent zarządzający stanem toggle:

<!-- Toggle.vue -->
<script setup>
import { ref } from 'vue'

const isOn = ref(false)

function toggle() {
  isOn.value = !isOn.value
}

function setOn() { isOn.value = true }
function setOff() { isOn.value = false }
</script>

<template>
  <slot :isOn="isOn" :toggle="toggle" :setOn="setOn" :setOff="setOff" />
</template>

Użycie w różnych kontekstach:

<template>
  <!-- Jako przełącznik -->
  <Toggle v-slot="{ isOn, toggle }">
    <button @click="toggle">
      System: {{ isOn ? 'AKTYWNY' : 'WYŁĄCZONY' }}
    </button>
  </Toggle>

  <!-- Jako panel rozwijany -->
  <Toggle v-slot="{ isOn, toggle }">
    <div>
      <h3 @click="toggle">Diagnostyka ▼</h3>
      <div v-if="isOn">Szczegóły systemu...</div>
    </div>
  </Toggle>
</template>

Functional Components

W Vue 3 każdy komponent z <script setup> jest już zoptymalizowany. Ale możesz też tworzyć proste komponenty funkcyjne jako zwykłe funkcje renderujące:

import { h } from 'vue'

// Functional component - nie ma stanu, tylko props
function StationBadge(props) {
  return h('span', {
    class: 'badge',
    style: {
      color: props.color || '#00ff88',
      border: '1px solid ' + (props.color || '#00ff88'),
      padding: '4px 12px',
      borderRadius: '12px',
      fontSize: '12px'
    }
  }, props.label)
}

StationBadge.props = ['label', 'color']

Użycie w szablonie:

<template>
  <StationBadge label="ONLINE" color="#2ecc71" />
  <StationBadge label="ALERT" color="#e74c3c" />
</template>

Render Functions z h()

Funkcja h() (hyperscript) tworzy VNode - wirtualny element DOM:

import { h } from 'vue'

// h(tag, props, children)
h('div', { class: 'panel' }, [
  h('h2', null, 'Tytuł'),
  h('p', null, 'Treść panelu')
])

Komponent z render function zamiast szablonu:

import { h, ref, defineComponent } from 'vue'

const Counter = defineComponent({
  setup() {
    const count = ref(0)

    return () => h('div', { class: 'counter' }, [
      h('p', null, 'Licznik: ' + count.value),
      h('button', {
        onClick: () => count.value++
      }, '+1')
    ])
  }
})

Higher-Order Components (HOC)

HOC to funkcja, która przyjmuje komponent i zwraca nowy komponent z dodaną funkcjonalnością:

import { h, ref, onMounted } from 'vue'

function withLoading(WrappedComponent) {
  return defineComponent({
    setup(props, { attrs }) {
      const loading = ref(true)

      onMounted(() => {
        setTimeout(() => {
          loading.value = false
        }, 1000)
      })

      return () => {
        if (loading.value) {
          return h('div', { class: 'loading' }, 'Ładowanie modułu...')
        }
        return h(WrappedComponent, { ...attrs })
      }
    }
  })
}

Użycie:

const MissionPanelWithLoading = withLoading(MissionPanel)

Kiedy używać tych wzorców?

WzorzecKiedy stosować
Renderless componentLogika wielokrotnego użytku z elastycznym UI
Functional componentProste, bezstanowe elementy prezentacyjne
Render function (h())Dynamiczne generowanie struktury DOM
HOCDodawanie zachowania do istniejących komponentów

Renderless components i scoped slots to idiomatyczny sposób Vue na separację logiki od prezentacji - szczególnie przydatny w systemach tak złożonych jak Centrum Dowodzenia NOVA LAB.

Kod do tej lekcji: App.vue
<script setup>
import { ref, h, defineComponent } from 'vue'

// Renderless Toggle component
const Toggle = defineComponent({
  setup(_, { slots }) {
    const isOn = ref(false)
    function toggle() { isOn.value = !isOn.value }
    function setOn() { isOn.value = true }
    function setOff() { isOn.value = false }

    return () => slots.default?.({
      isOn: isOn.value,
      toggle,
      setOn,
      setOff
    })
  }
})

// Functional component
function StationBadge(props) {
  return h('span', {
    style: {
      color: props.color || '#00ff88',
      border: '1px solid ' + (props.color || '#00ff88'),
      padding: '4px 12px',
      borderRadius: '12px',
      fontSize: '12px',
      display: 'inline-block'
    }
  }, props.label)
}
StationBadge.props = ['label', 'color']

// Counter with render function
const Counter = defineComponent({
  setup() {
    const count = ref(0)
    return () => h('div', { class: 'counter-box' }, [
      h('span', null, 'Licznik: ' + count.value),
      h('button', {
        onClick: () => count.value++,
        class: 'btn small',
        style: 'margin-left: 10px'
      }, '+1'),
      h('button', {
        onClick: () => count.value = 0,
        class: 'btn small reset',
        style: 'margin-left: 6px'
      }, 'Reset')
    ])
  }
})
</script>

<template>
  <div class="nova-lab">
    <h1>Renderless Components i Functional Patterns</h1>

    <section class="section">
      <h2>Renderless Toggle</h2>
      <Toggle v-slot="{ isOn, toggle }">
        <div>
          <button @click="toggle" :class="['btn', { active: isOn }]">
            System: {{ isOn ? 'AKTYWNY' : 'WYLACZONY' }}
          </button>
          <div v-if="isOn" class="panel">
            <p>Systemy diagnostyczne uruchomione.</p>
            <p>Temperatura: 22.5°C | Cisnienie: 1.01 atm</p>
          </div>
        </div>
      </Toggle>
    </section>

    <section class="section">
      <h2>Renderless Toggle - inny uzytek</h2>
      <Toggle v-slot="{ isOn, toggle }">
        <div>
          <h3 @click="toggle" class="expandable">
            {{ isOn ? '▼' : '▶' }} Logi stacji
          </h3>
          <ul v-if="isOn" class="log-list">
            <li>[09:15] System nawigacji OK</li>
            <li>[09:16] Skan sektora zakonczony</li>
            <li>[09:17] Synchronizacja danych</li>
          </ul>
        </div>
      </Toggle>
    </section>

    <section class="section">
      <h2>Functional Component - StationBadge</h2>
      <div class="badge-row">
        <StationBadge label="ONLINE" color="#2ecc71" />
        <StationBadge label="ALERT" color="#e74c3c" />
        <StationBadge label="STANDBY" color="#f39c12" />
        <StationBadge label="NOVA LAB" color="#00b4d8" />
      </div>
    </section>

    <section class="section">
      <h2>Render Function - Counter</h2>
      <Counter />
    </section>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #c0c0c0;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; }
h2 { color: #00b4d8; font-size: 16px; margin-bottom: 10px; }
h3 { color: #00ff88; margin: 0; }
.section {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid rgba(0, 180, 216, 0.2);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.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.active { background: #00ff88; color: #0a0e27; }
.btn.small { font-size: 12px; padding: 4px 10px; }
.btn.reset { color: #e74c3c; border-color: #e74c3c; }
.panel {
  margin-top: 10px;
  padding: 10px;
  background: rgba(0,255,136,0.05);
  border: 1px solid rgba(0,255,136,0.2);
  border-radius: 6px;
}
.panel p { margin: 4px 0; font-size: 13px; }
.expandable { cursor: pointer; user-select: none; }
.expandable:hover { color: #00b4d8; }
.log-list {
  list-style: none;
  padding: 0;
  margin: 8px 0 0;
}
.log-list li {
  padding: 4px 0;
  font-size: 13px;
  color: #888;
  border-bottom: 1px solid rgba(0,180,216,0.1);
}
.badge-row { display: flex; gap: 10px; flex-wrap: wrap; }
.counter-box {
  display: flex;
  align-items: center;
  padding: 10px;
  background: rgba(0,255,136,0.05);
  border-radius: 6px;
}
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Co to jest renderless component w Vue?

  2. 2. Jak renderless component przekazuje dane do komponentu-rodzica?

To 2 z 4 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    Zaimplementuj komponent Toggle z ref isOn, funkcją toggle i scoped slot.

  • Układanie w pionie

    Ułóż kroki tworzenia renderless component w poprawnej kolejności:

  • Klikanie w kolejności

    Ułóż poprawną kolejność argumentów funkcji h():

  • Edytor kodu

    Zaimplementuj StationBadge(props) jako funkcję zwracającą h('span', ...) z props.label i props.color.

  • Układanie w poziomie

    Ułóż poprawny import funkcji h z Vue:

  • Edytor kodu

    Zaimplementuj Counter z ref count i render function zwracającą h() z przyciskami +1 i Reset.

  • Układanie w pionie

    Ułóż wzorce od najprostszego do najbardziej zaawansowanego:

  1. PytanieRenderless component
  2. PytanieScoped slots w renderless component
  3. Zadanie z kodemPraktyka: Renderless Toggle
  4. Ułóż w kolejnościWzorzec renderless component
  5. PytanieFunkcja h() w Vue
  6. Kliknij w kolejnościArgumenty funkcji h()
  7. Zadanie z kodemPraktyka: Functional component
  8. Ułóż w kolejnościImport funkcji h()
  9. PytanieHigher-Order Component
  10. Zadanie z kodemPraktyka: Render function z h()
  11. Ułóż w kolejnościKiedy stosować wzorce zaawansowane

Przydatne artykuły