Pinia master course
  • ๐ŸIntroduction
    • Why Pinia
      • Introduction & Project setup
      • Vuex VS Pinia
  • ๐ŸŽEssential of Pinia
    • Create Store, State, Action, Getters
    • Use store in vue component
      • [Optional] ๊ตฌ์กฐ๋ถ„ํ•ด๋Š” ์™œ reactivity๋ฅผ ์žƒ๊ฒŒ ๋งŒ๋“ค๊นŒ?
      • ๋น„๋™๊ธฐ ์•ก์…˜ ์ƒ์„ฑํ•˜๊ธฐ
      • ๋กœ์ปฌ์Šคํ† ๋ฆฌ์ง€ ์‚ฌ์šฉํ•˜๊ธฐ
Powered by GitBook
On this page
  • Stores
  • ์Šคํ† ์–ด ์ƒ์„ฑํ•˜๊ธฐ
  • main.js
  • ์Šคํ† ์–ด ์ƒ์„ฑํ•˜๊ธฐ
  • State, getters, actions
  • State
  • Actions
  • Getters
  1. Essential of Pinia

Create Store, State, Action, Getters

Stores, State, Actions, Getters,

PreviousVuex VS PiniaNextUse store in vue component

Last updated 1 year ago

Stores

๋ชจ๋“ˆ VS ๋‹ค์ค‘ ์Šคํ† ์–ด๋“ฏ์ด Pinia์—์„œ๋Š” ์—ฌ๋Ÿฌ๊ฐœ์˜ ์Šคํ† ์–ด๊ฐ€ ์กด์žฌํ•˜๊ณ  ๊ฐ ์Šคํ† ์–ด๋Š” ํŠน์ • ๋„๋ฉ”์ธ์— ์ข…์†๋˜๋Š” ์ƒํƒœ๊ฐ’๋“ค์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.

์Šคํ† ์–ด ์ƒ์„ฑํ•˜๊ธฐ

stores/index.js

๋จผ์ € Pinia ์Šคํ† ์–ด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

import { createPinia } from "pinia";

export function setupPinia() {
  const pinia = createPinia()
  return pinia
}

main.js

์•ฑ์— ์—ฐ๊ฒฐํ•ด์ค๋‹ˆ๋‹ค.


const pinia =  setupPinia();

export const app = createApp(App)
  .use(pinia)
  .use(router)
  .use(logPlugin);

์Šคํ† ์–ด ์ƒ์„ฑํ•˜๊ธฐ


import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  // ...
})

defineStore api๋ฅผ ์‚ฌ์šฉํ•ด ๋ฆฌ์•กํŠธ์˜ ํ›…์„ ์„ ์–ธํ•˜๋“ฏ์ด ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

State, getters, actions

import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state:() => ({
    userData: null,
    loading: false,
    error: null
  }),
  getters: {
    isUserLoggedIn: state => !!state.userData,
  },
  actions: {
    async fetchUserData(userId) {
      this.loading = true;
      const response = await http.get("/user",{ userId});
      this.userData = response;
    }
  }
})

Vuex์™€ ๋‹ค๋ฅด๊ฒŒ mutation์ด ์—†์Šต๋‹ˆ๋‹ค.

actions์—์„œ ๋น„๋™๊ธฐ ํ˜ธ์ถœ๊ณผ ์ƒํƒœ ์—…๋ฐ์ดํŠธ๋ฅผ ๊ฐ™์ด ํ•˜๋ฉฐ getters๋Š” state ๊ฐ’์„ ์ด์šฉํ•ด computed ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

ํ•œ๊ฐ€์ง€ ์•„์‰ฌ์šด ์ ์€ this context๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋Š” ์ ์ž…๋‹ˆ๋‹ค.

State

๋ฐ˜์‘ํ˜• ๋ฐ์ดํ„ฐ๋ฅผ ์„ ์–ธํ•˜๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค.

์˜ˆ์ œ ์ฝ”๋“œ์—์„œ๋Š” ๋ฐ์ดํ„ฐ ํŒจ์นญ์„ ํ•  ๋•Œ ๋ณด์—ฌ์ง€๋Š” ๋กœ๋”ฉ ์ƒํƒœ๋“ค๋„ ๊ฐ™์ด ์„ ์–ธํ–ˆ์Šต๋‹ˆ๋‹ค.

Actions

๋น„๋™๊ธฐ ํ˜ธ์ถœ ํ˜น์€ ์ƒํƒœ ์—…๋ฐ์ดํŠธ๊ฐ€ ์ผ์–ด๋‚˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์ •์˜ํ•˜๋Š” ๊ณณ์ž…๋‹ˆ๋‹ค.

Getters

state์—์„œ ํŒŒ์ƒ๋œ ๊ฐ’๋“ค์„ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.

๐ŸŽ
์—ฌ๋Ÿฌ๊ฐœ์˜ ์Šคํ† ์–ด๋ฅผ ์ •์˜ํ•œ ๋ชจ์Šต