# Pinia
由於 Vuex 4.x 版本只是個過渡版,Vuex 4 對 TypeScript 和 Composition API 都不是很友好,雖然官方團隊在 GitHub 已有討論 Vuex 5 (opens new window)的開發提案,但從 2022-02-07 Vue 3 被設置為默認版本開始, **Pinia 也正式被官方推薦作為全局狀態管理的工具**。
### Vuex vs Pinia
- **移除 Mutations**
- Typescript 不再需要多餘的 types 來包裝
- 不再需要引入各種 magic string(...),直接引入函數,享受自動補全帶來的快樂
- 不再需要動態註冊模組,預設都是動態註冊
- 拋棄 Nested Module,在保持模組互相引入的前提下,採用 **Flat Module**,甚至可以進行 circular dependencies 讓兩模組互相調用(需注意可能產生無限迴圈)
- 無需 namespaced,所有模組都已**自動 namespaced**(~~namespced: true~~)
## Defining store
### createPinia
###### - mian.ts
```typescript=
import { createPinia } from "pinia";
createApp(App).use(createPinia()).mount("#app");
```
### defineStore
###### - myStore.ts
```typescript=
import { defineStore } from "pinia";
const productStore = defineStore("productStore", {
// the first argument is a unique id of the store
state: () => ({
productName: "Kelly",
counter: 1,
}),
getters: {},
actions: {},
});
export default productStore;
```
## Use store
###### - component.vue
> We are defining a store because the store won't be created **until useStore() is called** inside of setup()
```javascript=
import myStore from "../store/myStore";
const store = myStore();
```
### storeToRefs
https://juejin.cn/post/7054481067297734693
https://juejin.cn/post/7068483852674531335
## pinia-plugin-persist
> By enabling the persist plugin on your store, the whole state will be stored in the **sessionStorage** by default.
```
yarn add pinia-plugin-persist
```