Asosiy matnga o'tish
ITIT Interview
Vue.js

Komponentlar, props va emits

Komponent yaratish va ro'yxatdan o'tkazish, defineProps va defineEmits, bir yo'nalishli ma'lumot oqimi, komponentda v-model va defineModel, fallthrough atributlar.

O'rganildi: 0 / 4
Progress

Komponent

components/UserCard.vue
<script setup lang="ts">
const props = defineProps<{
  name: string;
  age?: number;
  role: 'admin' | 'user';
}>();

const emit = defineEmits<{
  select: [id: number];
  remove: [];
}>();
</script>

<template>
  <div class="card">
    <h3>{{ name }}</h3>
    <p v-if="age">{{ age }} yosh</p>
    <button @click="emit('select', 42)">Tanlash</button>
    <button @click="emit('remove')">O'chirish</button>
  </div>
</template>
App.vue
<script setup lang="ts">
import UserCard from './components/UserCard.vue';   // script setup'da import yetarli
</script>

<template>
  <UserCard name="Ali" :age="25" role="admin" @select="onSelect" @remove="onRemove" />
</template>

Props'da standart qiymat:

const props = withDefaults(defineProps<{ size?: 'sm' | 'md'; items?: string[] }>(), {
  size: 'md',
  items: () => [],       // obyekt va massivlar uchun funksiya
});
// Vue 3.5+: destrukturizatsiya bilan
const { size = 'md' } = defineProps<{ size?: 'sm' | 'md' }>();

Bir yo'nalishli ma'lumot oqimi

Ma'lumot pastga props orqali tushadi, o'zgarish haqida xabar yuqoriga emits orqali chiqadi.

// Xato: props'ni o'zgartirish
props.count++;           // ogohlantirish, ota komponentdagi ma'lumot buziladi

// To'g'ri: ota komponentga xabar berish
emit('update:count', props.count + 1);

// Yoki lokal nusxa
const localCount = ref(props.count);

Komponentda v-model

Vue 3.4+ da defineModel:

components/SearchInput.vue
<script setup lang="ts">
const model = defineModel<string>({ default: '' });
</script>

<template>
  <input v-model="model" placeholder="Qidirish..." />
</template>
<SearchInput v-model="query" />
<!-- aslida: :modelValue="query" @update:modelValue="query = $event" -->

Bir nechta v-model:

<UserForm v-model:first-name="first" v-model:last-name="last" />
const firstName = defineModel<string>('firstName');
const lastName = defineModel<string>('lastName');

Fallthrough atributlar

Props sifatida e'lon qilinmagan atributlar (class, id, @click va h.k.) komponentning ildiz elementiga avtomatik o'tadi:

<BaseButton class="primary" @click="save" />
<!-- BaseButton'ning ildiz button elementiga class va click qo'shiladi -->
<script setup>
defineOptions({ inheritAttrs: false });
</script>

<template>
  <label>
    <span>{{ label }}</span>
    <input v-bind="$attrs" />    <!-- atributlarni boshqa elementga yo'naltirish -->
  </label>
</template>

Dinamik va asinxron komponentlar

<component :is="currentTab === 'a' ? TabA : TabB" />
import { defineAsyncComponent } from 'vue';
const HeavyChart = defineAsyncComponent(() => import('./HeavyChart.vue'));   // alohida bundle

Intervyu savollari

Ushbu sahifada