vue2 和vue3 都适用,
pinia中只有 state getters actions 抛弃了mutations 减少了工作量 actions支持异步同步
良好的typescript支持
体积非常小 只有1kb左右
支持插件来扩展自身功能 支持服务端渲染
npm create vite@latest 选择vue vue-ts
//mainjs
import { createPinia } from 'pinia'
createApp(App).use(createPinia()).mount('#app')
//store/user.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore('mystore', {
state:()=>{
return {
count:3
}
},
getters: {
doubleCount: (state) => state.count * 2,
},
})
//使用
import { useCounterStore } from './store/user'
import { storeToRefs } from 'pinia'
const store = useCounterStore()
const { count } = storeToRefs(store)
function handleCount() {
store.count++
}
//重置
const reset = () => {
store.$reset()
}
//批量修改
const handle = () => {
store.$patch({
count: 0,
})
}
//直接替换
const handle = () => {
store.$state = {
count: 0,
name: "wode"
}
}
//# 数据持久化
插件 pinia-plugin-persist 可以辅助实现数据持久化功能。