[Vue] Vue3 ๐Ÿpinia ์‚ฌ์šฉ๋ฒ•

TATAยท2023๋…„ 10์›” 24์ผ
0

Vue

๋ชฉ๋ก ๋ณด๊ธฐ
2/3

โ–ท pinia

vue3์—์„œ ์ „์—ญ ์ƒํƒœ ๊ด€๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋Š” pinia

๐Ÿ ์„ค์น˜

npm install pinia

๐Ÿ pinia ์„ค์ •

main.js

import { createPinia } from 'pinia';

const app = createApp(App);
app.use(createPinia());

src/store/counter.js

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  // ์ดˆ๊ธฐ ์ƒํƒœ ์ง€์ •
  state: () => {
    return { count: 1 };
  },
  getters: {
    doubleCount: state => state.count * 2,
  },
  // ์•ก์…˜ ํ•จ์ˆ˜ ์ง€์ •
  actions: {
    increment() {
      this.count++;
    },
  },
});

๐Ÿ Setup Stores

Setup Stores

ref()๋Š” state ์†์„ฑ์ด ๋จ.
computed()๋Š” getters๊ฐ€ ๋จ.
function()์€ actions๊ฐ€ ๋จ.

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const name = ref('Eduardo')
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

๐Ÿ ์ƒํƒœ ๊ฐ€์ ธ์™€์„œ ์‚ฌ์šฉํ•˜๊ธฐ

<template>
  <div>
    <p>Count: {{ store.count }}</p>
    <p>Count: {{ store.doubleCount }}</p>
    <button @:click="store.increment()"></button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/store/counter';

const store = useCounterStore();
</script>

โž• typescript

import { defineStore } from 'pinia';

interface Counter {
  count: number;
}

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 1 } as Counter;
  },
  actions: {
    increament() {
      this.count++;
    },
  },
});

๐Ÿ storeToRefs

store์—์„œ ๊ทธ๋ƒฅ ๊ตฌ์กฐ ๋ถ„ํ•ด๋ฅผ ํ•˜๋ฉด ํ•ด๋‹น ๊ฐ์ฒด๊ฐ€ store์™€ ๋–จ์–ด์ง€๊ฒŒ ๋œ๋‹ค.
storeToRefs์„ ์จ์„œ ๊ตฌ์กฐ ๋ถ„ํ•ด๋ฅผ ํ•˜๋ฉด ๋ฐ˜์‘์„ฑ์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

import { useCounterStore } from '@/store/counter';
const store = useCounterStore();
// const { counter } = store;
const { counter } = storeToRefs(store);
const { increment } = store; // ํ•จ์ˆ˜๋Š” ๊ทธ๋ƒฅ ๊ฐ€์ ธ์˜ค๊ธฐ ๊ฐ€๋Šฅ
profile
๐Ÿพ

0๊ฐœ์˜ ๋Œ“๊ธ€