Create Store, State, Action, Getters
Stores, State, Actions, Getters,
Last updated
Stores, State, Actions, Getters,
Last updated
๋ชจ๋ VS ๋ค์ค ์คํ ์ด๋ฏ์ด Pinia์์๋ ์ฌ๋ฌ๊ฐ์ ์คํ ์ด๊ฐ ์กด์ฌํ๊ณ ๊ฐ ์คํ ์ด๋ ํน์ ๋๋ฉ์ธ์ ์ข ์๋๋ ์ํ๊ฐ๋ค์ ์ ์ํฉ๋๋ค.
๋จผ์ Pinia ์คํ ์ด๋ฅผ ์์ฑํฉ๋๋ค.
import { createPinia } from "pinia";
export function setupPinia() {
const pinia = createPinia()
return pinia
}
์ฑ์ ์ฐ๊ฒฐํด์ค๋๋ค.
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๋ฅผ ์ฌ์ฉํด ๋ฆฌ์กํธ์ ํ ์ ์ ์ธํ๋ฏ์ด ์์ฑํฉ๋๋ค.
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
์์ ํ์๋ ๊ฐ๋ค์ ์ ์ธํฉ๋๋ค.