vuex 는 vue 에서 상태관리를 편하게 하기위해서 사용한다
- 전역 상태 ( 거의 필수, token )
- 나머진 사용하기 나름 ( API , 페이지 상태 )
What is a Store?
A Store (like Pinia) is an entity holding state and business logic that isn't bound to your Component tree. In other words, it hosts global state. It's a bit like a component that is always there and that everybody can read off and write to. It has three concepts, the state, getters and actions and it's safe to assume these concepts are the equivalent of data, computed and methods in components.
Store은 언제 사용할까요?
store은 당신의 어플리케이션을 통해 접근할 수 있는 데이터가 포함되어 있어야 합니다.
이것은 여러 곳에서 사용할 수 있는 데이터를 포함합니다.
예시) User information that is displayed in the navbar, as well as data that needs to be preserved through pages, e.g. a very complicated multi-step form.
한편으론 컴포넌트로 호스트 할 수 있는 로컬데이터를 store에 포함하는 것을 피해야만 합니다.
On the other hand, you should avoid including in the store local data that could be hosted in a component instead, e.g. the visibility of an element local to a page.
모든 애플리케이션이 글로벌 스테이트에 접근해야 할 필요는 없지만 만약 필요한다면 Pinia를 쓰세요.
Store 정의하기
defineStore()를 통해 Store을 정의할 수 있습니다.
import { defineStore } from 'pinia'
// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useStore = defineStore('main', {
// other options...
})
Store 사용하기
ㅁㄴㅇ
src / stores / ProductStore.js
자바스크립트 파일을 만들고 이게 Pinia라는 것을 vue한테 알려주기 위해 필요한 것들
import { defineStore } from 'pinia';
//defineStore은 매개변수가 2개 필요하다.
//매개변수①: 유니크한 이름 (store name / id.)
//Pinia가 store을 개발툴에 연결시켜준다.
defineStore("ProductStore",
///매개변수②: options object
//state
//actions
//getter
)
export 하기 (useXXXXXX)
import { defineStore } from 'pinia';
export const userProductStore = defineStore("ProductStore",
)
매개변수② options object
import { defineStore } from 'pinia';
import products from '@/data/products.json';
export const userProductStore = defineStore("ProductStore",
state: () =>{
return {
products, (src/data/products.json)
}
}
// state는 initial state로 리턴되는 function으로 정의되어야 한다.
// state란? state는 store의 중심부분이다. 어플리케이션의 컴포넌트에 접근할 수 있는 data를 정의하기 위해 필요하다.
)
Pinia에서 json파일 import 하고 사용하기
import { defineStore } from 'pinia';
import products from '../data/products.json';
const useProductStore = defineStore('ProductStore', {
state: () => ({
products,
}),
});
export default useProductStore;
//export default const useProductStore; 때문에 생각 많이 했다.
<script setup>
import useProductStore from './stores/ProductStore';
useProductStore();
</script>
^ products.json 파일을 이용해서 상품리스트를 불러 온 것
^ pinia를 이용해서 상품리스트를 불러 온 것
^ 특정 부분만 가져오기
Pinia에서 API 적용하기
import { defineStore } from 'pinia';
import products from '../data/products.json';
const useProductStore = defineStore('ProductStore', {
state: () => ({
products:[]
//빈값으로 만들기
};),
actions: {
fill() {
this.products = products //products.json임
});
export default useProductStore;
Pinia에서 actions를 정의하려면 store에 actions 옵션을 넣고 methods를 정의하면 됩니다.
이렇게 바꿔도 페이지가 작동 안하는데 그건 fill을 안 불러와서 그런겁니다.
<script setup>
import useProductStore from './stores/ProductStore';
const productStore = useProductStore();
productStore.fill();
</script>
데이터를 비동기적으로 불러오는 법
import { defineStore } from 'pinia';
import products from '../data/products.json'; //static import
const useProductStore = defineStore('ProductStore', {
state: () => ({
products:[]
//빈값으로 만들기
};),
actions: {
async fill() { //async 추가
// static import: this.products = products //products.json임
// dynamic import
this.products = (await import('../src/data/products.json')).default
});
export default useProductStore;