export const useCounter = () => useState<number>('counterState', () => 0);
export const useColor = () => useState<string>('color', () => 'pink');
<script setup lang="ts">
const counter = useState('counter', () => Math.round(Math.random() * 1000));
const color = useColor(); // Same as useState('color')
const counterState = useCounter();
</script>
<template>
<div>
<div>
Counter: {{ counter }}
<button @click="counter++">+</button>
<button @click="counter--">-</button>
</div>
<div>
Counter: {{ counterState }}
<button @click="counterState++">+</button>
<button @click="counterState--">-</button>
</div>
<p>Current color: {{ color }}</p>
</div>
</template>
기존에 사용하던 store, composition API ? 형태로 수정 결과
import { defineStore } from 'pinia';
export const surveyStore = defineStore('survey', () => {
const surveyList = ref([]);
const apiResult = ref(0);
async function fetchSurveyList() {
try {
const res = await $fetch(`/backapi/selectList`, {
method: 'POST',
body: {
mapperName: 'survey.selectSurveyList',
params: { surveyId: 1 },
},
});
console.log(res.resMap);
surveyList.value = res.resMap.reduce((acc, obj) => {
const { questionId } = obj;
acc[questionId] = acc[questionId] ?? [];
acc[questionId].push(obj);
return acc;
}, {});
} catch (error) {
surveyList.value = [];
console.log(error);
}
}
return { surveyList, apiResult, fetchSurveyList };
});