728x90
Vue 3에서 Pinia를 사용하여 상태를 관리할 때, 예시로 count 값을 직접 입력하는 방법을 정리해보겠습니다.
(기록용)
1. 기본 Pinia 스토어 설정
먼저, stores/counter.ts 파일을 만들고 count 상태와 관련된 로직을 정의합니다.
import { defineStore } from "pinia";
import { ref } from "vue";
export const useCounterStore = defineStore("counter", () => {
const count = ref(0);
function setCount(value: number) {
count.value = value;
}
return { count, setCount };
});
- count: ref로 정의된 상태 변수
- setCount(value): count 값을 변경하는 메서드
2. 컴포넌트에서 count 직접 수정하는 방법
✅ 방법 1: v-model을 사용하여 count 값을 직접 수정
<script setup>
import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore();
</script>
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<input v-model.number="counterStore.count" type="number" />
</div>
</template>
- v-model.number을 사용하여 count 값을 직접 입력 가능
✅ 방법 2: $patch()를 사용하여 상태 변경
<script setup>
import { useCounterStore } from "@/stores/counter";
import { ref } from "vue";
const counterStore = useCounterStore();
const newValue = ref(0);
const updateCount = () => {
counterStore.$patch({ count: newValue.value });
};
</script>
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<input v-model.number="newValue" type="number" />
<button @click="updateCount">Set Count</button>
</div>
</template>
- $patch()를 사용하면 여러 상태를 한 번에 변경 가능
✅ 방법 3: setCount() 메서드를 사용하여 값 변경
<script setup>
import { useCounterStore } from "@/stores/counter";
import { ref } from "vue";
const counterStore = useCounterStore();
const newValue = ref(0);
</script>
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<input v-model.number="newValue" type="number" />
<button @click="counterStore.setCount(newValue)">Set Count</button>
</div>
</template>
- setCount() 메서드를 호출하여 count 값을 업데이트
✨ 정리
- v-model을 사용하면 count 값을 직접 수정 가능
- $patch()를 사용하면 여러 상태를 한 번에 업데이트 가능
- setCount() 메서드를 정의하여 count 값을 변경하는 방식도 활용 가능
※ Pinia의 $patch()는 스토어 상태를 한 번에 여러 개 업데이트할 수 있도록 해주는 API
728x90
반응형
'개발 | IT' 카테고리의 다른 글
AI는 사람을 대체하는가, 함께 갈 수 있는가? (2) | 2025.04.19 |
---|---|
로컬 프로젝트 생성 후 git에 등록하기 (0) | 2023.07.28 |
normalize() (0) | 2023.07.28 |
spring security 프로젝트 만들기 (0) | 2023.07.16 |