vuex|vuex5 Pinia状态管理

1、配置 import { createPinia } from 'pinia' app.use(createPinia())2、基本使用 (1)创建store .导出命名通过use开头import { defineStore } from 'pinia'方式一:通过之前vuex的配置项格式以及mapState等辅助函数的使用 const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ } } })组件中: export default { computed: { ...mapStores(useCounterStore, useUserStore) ...mapState(useCounterStore, ['count', 'double']), }, methods: { ...mapActions(useCounterStore, ['increment']), }, } 方式二:通过函数形式 export const useCounterStore = defineStore('counter', () => { const count = ref(0) function increment() { count.value++ }return { count, increment } }) (2)store使用 .导入定义的store .不要对导入的store的state进行解构赋值,否则会丢失其响应性 .actions可以直接进行解构import { storeToRefs } from 'pinia'export default defineComponent({ setup() { const store = useStore()不能使用解构赋值state,否则会丢失响应性 const { name, doubleCount } = store通过storeToRefs进行解构,不会丢失响应性 const { name, doubleCount } = storeToRefs(store)可以直接进行解构actions const { increment } = storereturn { doubleValue: computed(() => store.doubleCount), } }, }) (3)state使用 (1)改变state 方式一: store.counter++方式二: 选项式通过:mapState、mapWritableState辅助函数方式三:通过$patch (1)通过patch一个对象 .对于数组的push操作等,需要重新返回一个新对象store.$patch({ counter: store.counter + 1, name: 'Abalam', })(2)通过patch一个方法 .对于这种方式数组的push操作等直接在原对象操作即可store.$patch((state) => { state.items.push({ name: 'shoes', quantity: 1 }) state.hasChanged = true })(2)恢复、替换state 恢复state为初始化状态 store.$reset()替换整个state store.$state = { counter: 666, name: 'Paimon' } pinia.state.value = https://www.it610.com/article/{}; SSR使用(3)监听state修改方式一: .相比watch监听更能够追溯状态store.$subscribe((mutation, state) => { mutation: 修改方式 mutation.type'direct' | 'patch object' | 'patch function'修改的store名称 mutation.storeIdpatch的对象,只有当patch一个对象时才会有 mutation.payload},{ detached: true 监听器不会在组件卸载时移除,默认会 })方式二: watch( pinia.state, (state) => { ... }, { deep: true } )

    推荐阅读