Pinia

YuJin Lee·2022년 10월 2일
0

설치

npm install pinia

src/stores/counter.js

import { defineStore } from 'pinia'

// 컴포저블 함수와 마찬가지로 use로 시작하는 이름으로 만드는 것이 관례
// defineStore(스토어의 고유 아이디, 옵션)
// pinia를 잘 활용하기 위해서 각각의 스토어를 다른 파일로 나누는것을 권장
export const useCounterStore = defineStore('counter', {
  // 컴포넌트의 상태
  state: () => ({
    counter: 1,
  }),
  // 컴포넌트의 computed
  getters: {
    doubleCount: state => state.counter * 2,
    // getters에서도 this로 인스턴스에 접근하려면 일반함수 문법으로 사용해야 한다.
    doubleCountPlusOne() {
      return this.doubleCount + 1
    },
  },
  // 컴포넌트의 method
  actions: {
    // 화살표 함수를 사용하면 this로 store의 인스턴스에 접근할 수 없다.
    // 화살표 함수는 상위 스코프의 this에 영향을 받기 때문이다.
    increment() {
      this.counter++;
    }
  },
})

src/views/AboutView.vue

<template>
  <div>
    <h2>Store</h2>
    <p>counter: {{ counter }}</p>
    <p>doubleCount: {{ doubleCount }}</p>
    <p>doubleCountPlusOne: {{ doubleCountPlusOne }} </p>
    <button @click="increment()">click</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from "pinia";

const store = useCounterStore();

// 객체구조할당 방식으로 가져오면 reactive(반응성) 매핑이 끊어진다.
// number 타입으로 할당되어 값이 업데이트 되지 않는다.
// const { counter } = store;

// 이 때 state나 getters를 가져올 때 reactive를 유지하기 위해 storeToRefs를 사용한다.
const { counter, doubleCount, doubleCountPlusOne } = storeToRefs(store);

// actions를 가져올 때는 그냥 구조분해할당을 사용하면 된다.
const { increment } = store;

// state의 값을 변경시킬수도 있다.
counter.value = 100;
// 컴포넌트 내에 정의한 것 처럼 바로 사용이 가능하다.
increment();

</script>
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글