uniapp 中如何使用 pinia 状态管理并实现持久化?

位置:首页 / 新闻中心 / 新框架教程

新框架教程 Admin 2024-12-25 11:18:52 1325
前言
内容有帮助的可以直接复制代码
pinia简介
vue3发布以后,pinia也随着诞生, 代替 Vuex 做状态管理,比较直观的好处就是不用在区分 同步调用 和 异步调用 了,store 的修改动作 action 作为常规函数调用,而不是使用 dispatch 方法或者是 commit 去调用,当然最重要的还是对 TS 支持比较友好
uniapp 中使用
在uniapp中使用pinia与我们平时使用 npm 安装插件的方式略有不同
使用 HBuilder X 不需要手动安装,直接使用即可
直接在 main.js 引入相关代码:

import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';
export function createApp() {
    const app = createSSRApp(App);
    app.use(Pinia.createPinia());
    return {
        app,
        Pinia, // 此处必须将 Pinia 返回
    };
}

这样我们就可以全局使用pinia了
添加管理模块
这里我们以一个登录模块为例
在根目录创建文件store/account.js定义好相关属性

import { defineStore } from 'pinia'
export const useAccountStore = defineStore('account', {
    state: () => {
        return {
            account: '测试'
        }
    },
    actions: {
        login(account) {
            this.account = account
        }
    }
})

然后就可以在页面中使用了

import { useAccountStore } from '@/stores/account.js'
const account = useAccountStore()
// 调用 actions
account.login('测试123')

这里可以通过属性访问的方式调用方法,也可以将方法解构出来,具体看使用习惯即可
数据持久化
使用状态管理时,有时我们会有这样的需求,需要将状态管理的数据存储到本地缓存中,在页面刷新,或者下一次访问时依然生效,uniapp提供了uni.setStorageSync()方法支持各个平台将数据存在本地,单如果需要时每一个单独加不便于管理,这个时候可以使用持久化的缓存插件,会自动把pinia配置的数据存到本地
使用pinia-plugin-unistorage
插件市场导入插件
pinia-plugin-unistorage - DCloud 插件市场
配置main.js

import { createUnistorage } from './uni_modules/pinia-plugin-unistorage'
export function createApp() {
    const app = createSSRApp(App)
    
    // 状态管理
    const store = Pinia.createPinia()
    // 持久化
    store.use(createUnistorage())
    app.use(store)
    
    return {
        app,
        Pinia
    }
}

在需要持久化缓存的状态配置好开关,以account.js为例

import { defineStore } from 'pinia'
export const useAccountStore = defineStore('account', {
    unistorage: true, // 是否持久化
    state: () => {
        return {
            account: '测试'
        }
    },
    actions: {
        login(account) {
            this.account = account
        }
    }
})

配置好unistorage属性后,Pinia就会自动把相关数据存到缓存里啦。

以上就是“uniapp 中如何使用 pinia 状态管理并实现持久化?”的详细内容,更多请关注木子天禾科技其它相关文章!

15934152105 扫描微信