Vue
August 27

Computed properties

computed() method reaktiv va kuzatuvchan xususiyatlarni yaratish uchun ishlatiladi. Bu metod quyidagi asosiy xususiyatlarga ega:

  1. Create aggregate value: Boshqa reaktiv ma'lumotlarga asoslangan qiymatlarni hisoblaydi.
  2. Caching: Natijani keshlashtiradi va faqat bog'liq ma'lumotlar o'zgargandagina qayta hisoblaydi.
  3. Getter function: computed() ga uzatiladigan funksiya getter sifatida ishlaydi.
  4. Reactivity: Hisoblangan xususiyat o'zgarsa, undan foydalanuvchi komponentlar avtomatik ravishda yangilanadi.

Create aggregated value

import { computed, ref } from 'vue'

const user = reactive({
  firstName: 'Doniyor',
  lastName: 'Yusupov',
  status: 1
})

const statusMap = {
 0: 'Created',
 1: 'Verified'
}

const fullName = computed(() => `${user.firstName} ${user.lastName}`) // Doniyor Yusupov

const userStatus = computed(() => statusMap[user.status]) // 'Verified'

Bu Create aggregate value uchun misol edi. Ya'ni bir reactive object dan bir nechta reactive object larni create qilishimiz mumkin.

Caching

import { ref, computed } from 'vue'

const numbers = ref(Array.from({ length: 10000 }, (_, i) => i + 1))
const searchTerm = ref('')

const filteredAndSortedNumbers = computed(() => {
  return numbers.value
    .filter(num => num.toString().includes(searchTerm.value))
    .sort((a, b) => b - a)
    .slice(0, 100)
})

function useNumbers() {
  function updateSearchTerm(newTerm) {
    searchTerm.value = newTerm
  }

  return {
    filteredAndSortedNumbers,
    updateSearchTerm
  }
}
<template>
  <div>
    <input v-model="searchTerm" @input="updateSearchTerm" placeholder="Qidirish">
    <ul>
      <li v-for="num in filteredAndSortedNumbers" :key="num">{{ num }}</li>
    </ul>
    ...
    <ul>
      <li v-for="num in filteredAndSortedNumbers" :key="num">{{ num }}</li>
    </ul>
  </div>
</template>

<script setup>
const { filteredAndSortedNumbers, updateSearchTerm } = useNumbers()
</script>

Bu misolda:

  1. numbers - 10,000 ta elementdan iborat katta massiv.
  2. searchTerm - foydalanuvchi kiritadigan qidiruv so'zi.
  3. filteredAndSortedNumbers - hisoblangan xususiyat bo'lib, u quyidagi amallarni bajaradi:
    • Massivni filtrlaydi
    • Teskari tartibda saralaydi
    • Natijadan faqat birinchi 100 ta elementni oladi

Keshlashtirish afzalligi:

  1. Samaradorlik: filteredAndSortedNumbers faqat numbers yoki searchTerm o'zgargandagina qayta hisoblanadi. Aks holda, keshlashtirish natijasidan foydalaniladi.
  2. Takroriy hisob-kitoblardan qochish: Agar komponentda filteredAndSortedNumbersga bir necha marta murojaat qilinsa ham, hisob-kitob faqat bir marta bajariladi.
  3. Tezkorlik: Foydalanuvchi interfeysi sezilarli darajada tezroq ishlaydi, chunki murakkab hisob-kitoblar faqat zarur bo'lgandagina bajariladi.

Reacts only to reactive data change

computed() methodi faqat reactive data o'zgarsagina callback ishlaydi.

const now = computed(() => Date.now())
const counter = computed(() => localStorage.getItem('counter'))

Bu misollarda now va counter o'zgaruvchilari bir marta initialization paytida set qilinadi va boshqa o'zgarmaydi chunki Date ham localStorage ham reactive emas.

Writable computed - Not recommended

Ccomputed properties default holatda getter funksiyaga ega. Kamdan-kam hollarda sizga writable computed value kerak bo'ladi. Agar siz computed value ga yangi qiymat bermoqchi bo'lsangiz, Runtime warning chiqadi. Agar kerak bo'sa siz uni ham getter, ham setter funksiyalarni ta'minlash orqali yaratishingiz mumkin.

import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
  // getter
  get() {
    return firstName.value + ' ' + lastName.value
  },
  // setter
  set(newValue) {
    [firstName.value, lastName.value] = newValue.split(' ')
  }
})


Best practices

Computed getter funcsiyalar faqatgina Pure computation uchun va Side-effect lardan holi bo'lgan xolda ishlatilishi kerak. Masalan quyidagilarni computed bn ishlatmaslik lozim:
- DOM ga o'zgartirish kiritish
- boshqa state ni o'zgartirish
- async request lar ishlatish

Computed value ni mutate qilmang. Uni faqat source state o'zgargan holda o'zgaradigan va shu value orqali hisoblangan qiymat deb qabul qiling.

"Writable computed larchi?" deyishingiz mumkin.
Writable computedlarni tepadagi Anti-patternlar sabab ishlatish tavsiya etilmaydi. Source state o'zgarganda boshqa stateni o'zgartirish uchun yoki async request lar uchun esa bizda Watcher lar bor.

Watcher lar uchun ham alohida post yozamiz. Siz bilmagan va kutmagan narsalar bo'lishi mumkin. Stay tuned...

@peaceofcode