Create Store, State, Action, Getters
Stores, State, Actions, Getters,
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
์์ ํ์๋ ๊ฐ๋ค์ ์ ์ธํฉ๋๋ค.
Last updated