Pinia
对比Vuex
Vue3、Vue2都支持
抛弃Mutations、modules,只有state、getters、action
完整支持TS
轻巧、代码简洁
Get Started
install Pinia
npm init vite npm i piniause in Vue根组件(main.js)
import { createPinia } from 'pinia' createApp(App).use(createPinia()).mount('#app')define store/xxx.js
import { defineStore } from 'pinia' import { useOtherStore } from './other' export const useCounterStore = defineStore('counter', { state: () => { return { helloWorld: 'helloWorld', count: 0, phone: 18088881234, } }, //cache getters: { phoneHidden() { return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }, }, actions: { changeState() { this.count++ }, getOtherStore() { console.log(useOtherStore().prop) }, async fillData() { this.products = (await import("@/data/product.json")).default } }, })
修改state五种方式
$reset、$subscribe、$onAction
注意
组件里解构后就丢失响应,需使用storeToRefs
use mapWritableState in stead of mapState
Last updated