Asosiy matnga o'tish
ITIT Interview
Vue.js

Composables

Composable funksiyalar, mantiqni qayta ishlatish, useFetch va useLocalStorage misollari, mixin'lar bilan solishtirish, MaybeRef va toValue, VueUse kutubxonasi.

O'rganildi: 0 / 4
Progress

Bu nima?

Composable — Composition API yordamida holatli mantiqni inkapsulyatsiya qiladigan va qayta ishlatiladigan funksiya. Nomi odatda use bilan boshlanadi. React'dagi custom hooklarga o'xshaydi.

composables/useCounter.ts
import { ref, computed } from 'vue';

export function useCounter(initial = 0) {
  const count = ref(initial);
  const double = computed(() => count.value * 2);
  const increment = () => count.value++;
  const reset = () => (count.value = initial);
  return { count, double, increment, reset };
}
<script setup>
import { useCounter } from '@/composables/useCounter';
const { count, double, increment } = useCounter(10);
</script>

Har bir chaqiruv o'z holatini yaratadi. Holat umumiy bo'lishi kerak bo'lsa, ref ni funksiyadan tashqarida e'lon qiling yoki Pinia ishlating.

useFetch

composables/useFetch.ts
import { ref, watchEffect, toValue, type MaybeRefOrGetter } from 'vue';

export function useFetch<T>(url: MaybeRefOrGetter<string>) {
  const data = ref<T | null>(null);
  const error = ref<Error | null>(null);
  const loading = ref(false);

  watchEffect(async (onCleanup) => {
    const controller = new AbortController();
    onCleanup(() => controller.abort());
    loading.value = true;
    error.value = null;
    try {
      const res = await fetch(toValue(url), { signal: controller.signal });
      data.value = await res.json();
    } catch (e) {
      if ((e as Error).name !== 'AbortError') error.value = e as Error;
    } finally {
      loading.value = false;
    }
  });

  return { data, error, loading };
}
<script setup lang="ts">
const userId = ref(1);
const { data: user, loading } = useFetch<User>(() => `/api/users/${userId.value}`);
// userId o'zgarsa, so'rov avtomatik qayta yuboriladi
</script>

toValue oddiy qiymat, ref yoki getter funksiyani bir xil qabul qiladi: composable moslashuvchan bo'ladi.

useLocalStorage

composables/useLocalStorage.ts
import { ref, watch } from 'vue';

export function useLocalStorage<T>(key: string, initial: T) {
  const stored = localStorage.getItem(key);
  const value = ref<T>(stored ? JSON.parse(stored) : initial);
  watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true });
  return value;
}

Hodisa tinglovchilarini tozalash

composables/useEventListener.ts
import { onMounted, onUnmounted } from 'vue';

export function useEventListener(target: EventTarget, event: string, handler: EventListener) {
  onMounted(() => target.addEventListener(event, handler));
  onUnmounted(() => target.removeEventListener(event, handler));
}

Composable ichidagi lifecycle hooklar uni chaqirgan komponentga bog'lanadi, shuning uchun tozalash avtomatik bo'ladi.

Composable va mixin

Mixin (Vue 2)Composable
Ma'lumot manbasiNoaniq: this.x qaysi mixin'dan?Aniq: destrukturizatsiya qilingan
Nom to'qnashuviBo'lishi mumkinQayta nomlash oson
ParametrlarYo'qFunksiya argumentlari
TypeScriptYomonTo'liq

VueUse

VueUse — 200 dan ortiq tayyor composable'lar to'plami: useStorage, useDebounceFn, useIntersectionObserver, useDark, useClipboard va boshqalar. O'zingiz yozishdan oldin u yerdan qidiring.

Intervyu savollari

Ushbu sahifada