在UniApp开发中推荐使用Pinia而非ucs-share状态管理
简要目的
在UniApp开发中,状态管理是一个关键环节。虽然ucs-share作为专为UniApp设计的状态共享插件有其优势,但我更推荐使用Pinia作为状态管理解决方案。因为在使用ucs-share的时候,当时我搭配 秋云 ucharts echarts 高性能跨全端图表组件使用时,传递数据的时候在js控制台打印data明明已经更新了,但是页面数据死活没有变化,无奈之下,搞了两天之后决定放弃ucs-share,改用Pinia插件之后就没有这个问题了。说明:选择真的很重要!
核心优势:Pinia的持续响应式特性
Pinia最大的优势在于其真正的响应式系统,而ucs-share在值传递时容易失去响应性:
// Pinia示例 - 保持响应式
const store = useStore()
const count = store.count // 保持响应式连接
// ucs-share示例 - 值传递可能失去响应式
const count = ucsShare.getState().count // 可能只是静态值
详细对比
- 响应式机制
Pinia:基于Vue3的reactive系统,所有状态变更自动触发视图更新
ucs-share:需要手动触发更新,值传递后可能失去响应性
- TypeScript支持
Pinia:一流的TypeScript支持,完整的类型推断
ucs-share:TypeScript支持有限
-
开发体验
Pinia:清晰的store结构
组合式API风格
DevTools集成
ucs-share:
相对简单的API
缺少专业开发工具支持
- 跨平台兼容性
Pinia:不仅适用于UniApp,也适用于所有Vue3环境
ucs-share:专为UniApp设计(但是响应式有待提高)
uniapp集成Pinia
hbuilderx 创建的 uniapp 项目
直接插件市场安装后引入注册
// main.js
import { createSSRApp } from "vue";
import * as Pinia from "pinia";
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, // 此处必须将 Pinia 返回
};
}
基础
import { defineStore } from "pinia";
export const useStore = defineStore("main", {
state() {
return {
someState: "hello pinia",
};
},
unistorage: true, // 开启后对 state 的数据读写都将持久化
});
或者 setup 语法也是支持的
import { defineStore } from "pinia";
export const useStore = defineStore(
"main",
() => {
const someState = ref("hello pinia");
return { someState };
},
{
unistorage: true, // 开启后对 state 的数据读写都将持久化
},
);
选项
钩子
import { defineStore } from "pinia";
export const useStore = defineStore("main", {
state() {
return {
someState: "hello pinia",
};
},
unistorage: {
// 初始化恢复前触发
beforeRestore(ctx) {},
// 初始化恢复后触发
afterRestore(ctx) {},
},
});
最后
可以将pinia模块化,毕竟项目大的时候共享数据需要分模块使用。

在/store/index.js文件中
import {
appStore
} from "./modules/app.js"
const userStore = () => ({
app: appStore(),
});
export default userStore;
在/srore/modules/app.js文件中
import {
defineStore
} from 'pinia'
export const appStore = defineStore('app', {
unistorage: false, // 是否持久化到内存
state: () => {
return {
/**
* 甲醛
*/
methanal: 0,
tvoc: 0,
/**
* 温度
*/
temperature: 0,
co2: 0,
/**
* 湿度
*/
humidity: 0,
/**
* 蓝牙是否已经连接
*/
connect: false,
}
},
actions: {
login(account) {
this.connectDevice = connectDevice;
}
}
})
后面新添的文件直接写在index.js文件中即可。
使用:
<template>
<view>
{{methanal}}
</view>
</template>
<script>
import userStore from "@/store/index.js"
const {
app,
} = userStore();
export default {
data() {
return {
str_undefined: "--",
};
},
onReady() {
},
onShow(e) {
console.log("onshow页面...", e);
},
onHide() {
},
onUnload() {
},
computed: {
methanal() {
return app.methanal;
}
其他......
}
謝謝觀看!(完)

3679

被折叠的 条评论
为什么被折叠?



