官網(wǎng)鏈接??:https://pinia.vuejs.org/introduction.html
一刹淌、 什么是pinia? /pi?nj?/
它是最新一代的輕量級(jí)狀態(tài)管理插件烘豌,相似于vuex宏怔。
二忱辅、 應(yīng)用場(chǎng)景
vue3.0+ts+vite+pinia = ??
三呈昔、用法
- 安裝
yarn add pinia
# or with npm
npm install pinia
- 全局注冊(cè)
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
- 通過(guò)defineStore來(lái)簡(jiǎn)單創(chuàng)建一個(gè)存儲(chǔ)管理
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...
})
- 應(yīng)用
import { useStore } from '@/stores/counter'
export default {
setup() {
const store = useStore()
return {
// you can return the whole store instance to use it in the template
store,
}
},
}
四顶捷、優(yōu)點(diǎn)
- 簡(jiǎn)便,存儲(chǔ)和組件變得很類似翰蠢,你可以輕松寫(xiě)出優(yōu)雅的存儲(chǔ)项乒。
- 類型安全,通過(guò)類型推斷梁沧,可以提供自動(dòng)完成的功能檀何。
- vue devtools 支持,可以方便進(jìn)行調(diào)試廷支。
- Pinia 支持?jǐn)U展频鉴,可以非常方便地通過(guò)本地存儲(chǔ),事物等進(jìn)行擴(kuò)展恋拍。
- 模塊化設(shè)計(jì)垛孔,通過(guò)構(gòu)建多個(gè)存儲(chǔ)模塊,可以讓程序自動(dòng)拆分它們芝囤。
- 非常輕巧似炎,只有大約 1kb 的大小辛萍。
- 服務(wù)器端渲染支持