vue3์์ ์ ์ญ ์ํ ๊ด๋ฆฌ๋ฅผ ํ ์ ์๋ pinia
npm install 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++;
},
},
});
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++;
},
},
});
store์์ ๊ทธ๋ฅ ๊ตฌ์กฐ ๋ถํด๋ฅผ ํ๋ฉด ํด๋น ๊ฐ์ฒด๊ฐ store์ ๋จ์ด์ง๊ฒ ๋๋ค.
storeToRefs์ ์จ์ ๊ตฌ์กฐ ๋ถํด๋ฅผ ํ๋ฉด ๋ฐ์์ฑ์ ์ ์งํ ์ ์๋ค.
import { useCounterStore } from '@/store/counter';
const store = useCounterStore();
// const { counter } = store;
const { counter } = storeToRefs(store);
const { increment } = store; // ํจ์๋ ๊ทธ๋ฅ ๊ฐ์ ธ์ค๊ธฐ ๊ฐ๋ฅ