vue 状态管理最佳实践探讨

43 阅读1分钟

状态管理库选择

vuex

  • Vuex是Vue.js官方出品的状态管理库,

pinia

  • Pinia则是一个较新的状态管理库,相比Vuex,
    • 简化了核心概念
    • setup store 与 Vue 组合式 API 的 setup 函数 有异曲同工之妙,而且也提供options store保留Vuex用法
    • 插件支持,如持久化
    • 极致轻量化,开发工具支持
    • 调用useStore()才会执行storeSetup逻辑
    • ......

pinia-plugin-persistedstate

  • 基本使用
import {ref, computed} from 'vue'
import {defineStore} from 'pinia'

/**
 *
 *
 * */
export const useDemoSetupStore = defineStore(
    "DemoSetupStore",
    () => {
        const count = ref(12)
        // pinia-plugin-persistedstate 从本地恢复是异步的,立即使用时获取的是默认值,并不是本地值
        // 若想立即能使用该数据
        // 使用watch,watchEffect等,但有性能开销
        // 推荐:useStorage
        console.log("count",count)
        const doubleCount = computed(() => count.value * 2)

        function increment() {
            count.value++
        }

        async function getData() {
        }

        return {
            // navs: ref(navs),
            count,
            doubleCount,
            increment,
        }
    },
    {
        // pinia-plugin-persistedstate
        // persist:true
        persist: {
            // key: 'storekey', //使用默认就行store.$id
            // storage:localStorage,//localStorage sessionStorage
            // 没有在storeSetup中return的属性不会持久化
            // 还需要其中某一个被更改才会触发持久化
            paths: ['count', 'obj.pro'],
            // serializer: {
            //     deserialize: parse,
            //     serialize: stringify,
            // },
            debug: true,
            beforeRestore: (ctx) => {
                console.log(`即将恢复 '${ctx.store.$id}'`)
            },
            afterRestore: (ctx) => {
                console.log(`刚刚恢复完 '${ctx.store.$id}'`)
            },
        }
    }
)