Asosiy matnga o'tish
ITIT Interview
Vue.js

Slotlar va provide/inject

Oddiy, nomlangan va scoped slotlar, fallback kontent, provide va inject bilan chuqur ma'lumot uzatish, prop drilling, reaktiv provide va InjectionKey.

O'rganildi: 0 / 4
Progress

Slotlar

Slot — ota komponent bola komponent ichiga shablon kontenti joylashi uchun joy. React'dagi children ga o'xshaydi.

BaseCard.vue
<template>
  <div class="card">
    <header><slot name="header">Sarlavha yo'q</slot></header>   <!-- fallback -->
    <main><slot /></main>                                         <!-- standart slot -->
    <footer><slot name="footer" /></footer>
  </div>
</template>
<BaseCard>
  <template #header><h2>Profil</h2></template>
  <p>Asosiy kontent</p>
  <template #footer><button>Saqlash</button></template>
</BaseCard>

#header — v-slot:header ning qisqa yozuvi.

Scoped slotlar

Bola komponent slotga ma'lumot uzatadi, ota esa uni qanday ko'rsatishni hal qiladi:

DataList.vue
<script setup lang="ts" generic="T">
defineProps<{ items: T[] }>();
</script>

<template>
  <ul>
    <li v-for="(item, index) in items" :key="index">
      <slot :item="item" :index="index" />
    </li>
  </ul>
</template>
<DataList :items="users">
  <template #default="{ item, index }">
    {{ index + 1 }}. <strong>{{ item.name }}</strong> — {{ item.email }}
  </template>
</DataList>

Bu render props naqshining Vue'dagi ekvivalenti: mantiq (ro'yxat, jadval, saralash) bola komponentda, ko'rinish esa ota komponentda.

Prop drilling muammosi

App (theme) → Layout → Sidebar → Menu → MenuItem (theme kerak)

Oraliq komponentlar theme dan foydalanmaydi, lekin uni uzatishga majbur. Yechim: provide / inject yoki Pinia.

provide va inject

keys.ts
import type { InjectionKey, Ref } from 'vue';

export const ThemeKey: InjectionKey<{ theme: Ref<string>; toggle: () => void }> = Symbol('theme');
App.vue
<script setup lang="ts">
import { provide, ref, readonly } from 'vue';
import { ThemeKey } from './keys';

const theme = ref('light');
const toggle = () => (theme.value = theme.value === 'light' ? 'dark' : 'light');

provide(ThemeKey, { theme: readonly(theme), toggle });
</script>
MenuItem.vue
<script setup lang="ts">
import { inject } from 'vue';
import { ThemeKey } from './keys';

const { theme, toggle } = inject(ThemeKey)!;    // istalgan chuqurlikdagi bola
</script>

Tavsiyalar:

  • ref ni berish orqali reaktivlik saqlanadi.
  • O'zgartirish funksiyasini ham provide qiling, bola esa qiymatni readonly holda oladi: ma'lumot faqat bir joyda o'zgaradi.
  • Kalit uchun Symbol va InjectionKey: nom to'qnashuvi yo'q va TypeScript turi saqlanadi.
  • inject(Key, standartQiymat) bilan provider bo'lmagan holat.

provide/inject va Pinia

provide/injectPinia
Ko'lamiKomponent daraxtining bir qismiGlobal
QachonKutubxona komponentlari (Tabs, Form), mavzu, lokal kontekstIlova bo'ylab state: foydalanuvchi, savat
DevToolsCheklanganTo'liq

Intervyu savollari

Ushbu sahifada