Asosiy matnga o'tish
ITIT Interview
Vue.js

computed va watch

computed xususiyatlar va keshlash, yoziladigan computed, watch va watchEffect farqi, deep va immediate opsiyalari, tozalash va metod bilan solishtirish.

O'rganildi: 0 / 5
Progress

computed

Boshqa reaktiv ma'lumotdan hisoblangan qiymat. Natija keshlanadi va faqat bog'liqliklari o'zgarganda qayta hisoblanadi.

<script setup lang="ts">
import { ref, computed } from 'vue';

const items = ref([
  { name: 'Telefon', price: 3500000, qty: 1 },
  { name: 'Quloqchin', price: 250000, qty: 2 },
]);
const search = ref('');

const total = computed(() => items.value.reduce((s, i) => s + i.price * i.qty, 0));
const filtered = computed(() =>
  items.value.filter((i) => i.name.toLowerCase().includes(search.value.toLowerCase())),
);
</script>

<template>
  <input v-model="search" />
  <li v-for="item in filtered" :key="item.name">{{ item.name }}</li>
  <p>Jami: {{ total }}</p>
</template>

computed va metod

<p>{{ total }}</p>          <!-- computed: keshlangan -->
<p>{{ getTotal() }}</p>     <!-- metod: har render'da qayta chaqiriladi -->

Bir xil natija, lekin computed bog'liqliklar o'zgarmaguncha qayta hisoblamaydi.

Yoziladigan computed

const firstName = ref('Ali');
const lastName = ref('Valiyev');

const fullName = computed({
  get: () => `${firstName.value} ${lastName.value}`,
  set: (value: string) => {
    [firstName.value, lastName.value] = value.split(' ');
  },
});

computed ichida yon ta'sirlar qilmang: API so'rovi, DOM o'zgartirish, boshqa state'ni o'zgartirish. U faqat qiymat qaytarishi kerak.

watch

Ma'lumot o'zgarganda yon ta'sir bajarish: API so'rovi, localStorage ga yozish, log.

import { ref, watch } from 'vue';

const query = ref('');
const results = ref([]);

watch(query, async (newValue, oldValue) => {
  if (newValue.length < 2) return;
  results.value = await searchApi(newValue);
});

// Bir nechta manba
watch([page, sort], ([newPage, newSort]) => loadData(newPage, newSort));

// reactive obyektning bitta xususiyati — getter bilan
watch(() => form.email, (email) => validate(email));

// Opsiyalar
watch(settings, save, { deep: true });          // ichma-ich o'zgarishlar
watch(userId, loadUser, { immediate: true });   // darhol ham bir marta
watch(token, refresh, { once: true });

Tozalash

Eski so'rovni bekor qilish (poyga holatining oldini olish):

watch(query, async (q, _old, onCleanup) => {
  const controller = new AbortController();
  onCleanup(() => controller.abort());
  results.value = await fetch(`/api/search?q=${q}`, { signal: controller.signal }).then((r) => r.json());
});

watchEffect

Bog'liqliklarni avtomatik aniqlaydi va darhol bir marta ishlaydi:

import { watchEffect } from 'vue';

watchEffect(() => {
  document.title = `${unread.value} ta yangi xabar`;   // unread o'zgarsa qayta ishlaydi
});
watchwatchEffect
ManbaAniq ko'rsatiladiIchida o'qilganlar avtomatik
Birinchi ishga tushishO'zgarishda (immediate bo'lmasa)Darhol
Eski qiymatBorYo'q
QachonAniq manbaga reaksiya, eski qiymat kerakBir nechta bog'liqlikli oddiy effektlar

Intervyu savollari

Ushbu sahifada