Asosiy matnga o'tish
ITIT Interview
Vue.js

Pinia

Pinia bilan global state boshqaruvi, setup va options store'lar, state, getters va actions, storeToRefs, store'lar orasidagi bog'liqlik, Vuex bilan solishtirish.

O'rganildi: 0 / 5
Progress

Bu nima?

Pinia — Vue'ning rasmiy state boshqaruv kutubxonasi (Vuex o'rnini egalladi). Bir nechta komponent ishlatadigan global holatni saqlaydi: foydalanuvchi, savat, sozlamalar.

main.ts
import { createPinia } from 'pinia';
createApp(App).use(createPinia()).mount('#app');

Setup store

Composition API uslubida (tavsiya etiladi):

stores/cart.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useCartStore = defineStore('cart', () => {
  // state
  const items = ref<{ id: number; name: string; price: number; qty: number }[]>([]);

  // getters
  const total = computed(() => items.value.reduce((s, i) => s + i.price * i.qty, 0));
  const count = computed(() => items.value.reduce((s, i) => s + i.qty, 0));

  // actions
  function add(product: { id: number; name: string; price: number }) {
    const existing = items.value.find((i) => i.id === product.id);
    if (existing) existing.qty++;
    else items.value.push({ ...product, qty: 1 });
  }

  async function checkout() {
    await api.post('/orders', items.value);
    items.value = [];
  }

  return { items, total, count, add, checkout };
});

Options store

stores/user.ts
export const useUserStore = defineStore('user', {
  state: () => ({ user: null as User | null, token: '' }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    async login(email: string, password: string) {
      const res = await api.post('/login', { email, password });
      this.user = res.user;
      this.token = res.token;
    },
    logout() {
      this.$reset();      // boshlang'ich holatga (faqat options store'da tayyor)
    },
  },
});

Komponentda ishlatish

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/stores/cart';

const cart = useCartStore();

// Xato: destrukturizatsiya reaktivlikni yo'qotadi
// const { total } = cart;

// To'g'ri: state va getters uchun storeToRefs, actions to'g'ridan-to'g'ri
const { items, total } = storeToRefs(cart);
const { add } = cart;
</script>

<template>
  <p>Jami: {{ total }} ({{ cart.count }} ta)</p>
  <button @click="add(product)">Savatga</button>
</template>

Bir nechta o'zgarishni birga qo'llash va kuzatish:

cart.$patch({ items: [] });
cart.$subscribe((mutation, state) => localStorage.setItem('cart', JSON.stringify(state.items)));

Store'lar orasida

export const useOrderStore = defineStore('order', () => {
  const cart = useCartStore();      // boshqa store'ni ichida chaqirish
  const user = useUserStore();
  async function place() {
    if (!user.isLoggedIn) throw new Error('Avval kiring');
    await cart.checkout();
  }
  return { place };
});

Pinia va Vuex

VuexPinia
MutationsMajburiyYo'q: actions to'g'ridan-to'g'ri o'zgartiradi
ModullarBitta store va ichma-ich modullarHar biri alohida store
TypeScriptMurakkabTo'liq tur chiqarish
HajmiKattaroq~1.5 KB
Composition APICheklanganSetup store'lar

Intervyu savollari

Ushbu sahifada