본문 바로가기
IT/Pinia

Vue3 ) script setup

by 2T1 2023. 3. 28.

내가 Pinia를 Vue3의 script setup으로 사용할 때, 쓰는 법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// store.js
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useStore = defineStore('store', () => {
  const count = ref(0);

  const increase = (n = 1=> {
    count.value += n;
  };
  const reset = () => {
    count.value = 0;
  };

  return { count, increase, reset };
});
 
cs

chrome의 vue devtools로 변수를 보고 싶다면 store.js에서 return 값으로 변수를 내보내함.

 

 

함수와 변수를 따로 가져와야하는게 좀 헷갈리긴 하지만 의외로 편하다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// main.vue
<script setup>
import { storeToRefs } from 'pinia';
import { useStore } from '@/store/store';
 
const store = useStore();
const { increase, reset } = store;
const { count } = storeToRefs(store);
</script>
 
<template>
  <div>
    <p>count : {{ count }}</p>
    <button type="button" @click="increase(1)">Increase : 1</button>
    <button type="button" @click="increase(2)">Increase : 2</button>
    <button type="button" @click="reset">reset</button>
  </div>
</template>
 
cs

'IT > Pinia' 카테고리의 다른 글

Pinia - Action ( Option Store )  (0) 2023.01.02
Pinia - Getter ( Option Store )  (0) 2023.01.02
Pinia - State ( Option Store )  (0) 2023.01.02
Pinia  (0) 2022.12.30