Commit 0824a866 by liimin

feat(store): 重构状态管理为基于类的模块化架构

- 新增 update、point、boutique、sys、audio、user 等模块,均使用 Class 定义状态类型
- 重构 store/index.uts 为模块化架构,支持动态注册和类型安全的 RootState
- 新增 store/README.md 详细说明新的架构和使用方式
- 更新迁移文档,反映新的状态管理最佳实践
- 添加测试页面和测试用例验证 store 功能
- 重构 reception 模块以符合新的代码风格
1 parent 490382b4
...@@ -8,11 +8,11 @@ ...@@ -8,11 +8,11 @@
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| |------|------|
| `store.state.boutique` | `(store.state as UTSJSONObject)['boutique']` | | `store.state.boutique` (弱类型) | **直接导入 state**: `import { state } from '@/store/index.uts'` |
| `store.state.user.xxx` | `(store.state as UTSJSONObject)['user']` 再取子属性 | | `store.state.user.xxx` | `state.user.xxx` (强类型访问) |
| 直接 `state.xxx` 跨模块 | 同上,或用 `dispatch` 更新 | | 直接 `this.$store.state` | Options API 中使用 `mapState` |
**原因**:UTS 对 reactive 跨模块类型推断不足,`store.state.xxx` 易报「找不到 xxx」。 **更新**: 现在 Store 使用 Class 定义 `RootState`,直接导入 `state` 对象即可获得完整的类型推断和代码提示。不再建议将 `state` 强转为 `UTSJSONObject`。
--- ---
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| |------|------|
| `ref(null as any)` | `ref<any \| null>(null)` | | `ref(null as any)` | `ref<any | null>(null)` |
| `ref<Comp>(null)` 组件 ref | `ref<any \| null>(null)` | | `ref<Comp>(null)` 组件 ref | `ref<any | null>(null)` |
**原因**:`null as any` 在 Kotlin 编译后可能 NPE。 **原因**:`null as any` 在 Kotlin 编译后可能 NPE。
...@@ -53,7 +53,7 @@ function getPkg(item: any, key: string): any { ...@@ -53,7 +53,7 @@ function getPkg(item: any, key: string): any {
| 禁止 | 推荐 | | 禁止 | 推荐 |
|------|------| |------|------|
| `Record<number, X>` + `{ 1: {...}, 0: {...} }` | 用函数映射 | | `Record<number, X>` + `{ 1: {...}, 0: {...} }` | 用函数映射 |
| `const map = { 1: a, 0: b } as Record<number, X>` | `function getXxx(id: number): X \| null` | | `const map = { 1: a, 0: b } as Record<number, X>` | `function getXxx(id: number): X | null` |
```uts ```uts
function getSceneTypeItem(sceneId: number): SceneTypeItem | null { function getSceneTypeItem(sceneId: number): SceneTypeItem | null {
...@@ -103,105 +103,4 @@ function parseStorageJson(key: string): UTSJSONObject | null { ...@@ -103,105 +103,4 @@ function parseStorageJson(key: string): UTSJSONObject | null {
} }
``` ```
**原因**:Android 可能返回 string;`JSON.parse("")` 抛错。 **原因**:JSON.parse 空字符串会崩溃。
---
## 七、Store dispatch 返回值
| 禁止 | 推荐 |
|------|------|
| `return null as any` | `return ({} as any)` |
**原因**:Kotlin Any 非空,`null as any` 易 NPE。
---
## 八、组件 ref 调用 expose 方法
| 禁止 | 推荐 |
|------|------|
| 在 onShow 中直接 `homeRef.value.updateApp()` | `setTimeout` + `callExposedMethod` |
```uts
setTimeout((): void => {
const home = homeRef.value
if (home != null) {
callExposedMethod(home, 'updateApp')
}
}, 0)
function callExposedMethod(comp: any, methodName: string): void {
if (comp == null) return
const obj = comp as UTSJSONObject
const fn = obj[methodName]
if (fn != null) {
(fn as () => void)()
}
}
```
**原因**:onShow 回调中直接调用易触发 ClassCastException(ReactiveObject → Void)。
---
## 九、API 返回与 State 类型
| 禁止 | 推荐 |
|------|------|
| `baseConfigData: Record<string, any>` 存 API 返回 | `baseConfigData: UTSJSONObject` |
| API 返回 UTSJSONObject 赋给 Record | 统一用 UTSJSONObject |
**原因**:Record 与 UTSJSONObject 在 Kotlin 侧转换不兼容。
---
## 十、uni 全局扩展
| 禁止 | 推荐 |
|------|------|
| `uni.$api` | `(uni as UTSJSONObject)['$api']` |
| `uni.$logger` | 同上 |
```uts
function getUni(name: string): any | null {
return (uni as UTSJSONObject)[name] ?? null
}
```
**原因**:UTS 无法识别挂载在 uni 上的自定义属性。
---
## 十一、数组判断
| 禁止 | 推荐 |
|------|------|
| `Array.isArray(arr) && arr.length` | `arr instanceof Array` + 长度判断 |
| `arr.length > 0`(arr 为 any) | `(arr as any[]).length > 0` 或先 instanceof |
**原因**:UTS 对 Array 推断与 length 访问有约束。
---
## 十二、迁移单文件时的顺序
1. 打开目标文件,全文搜索并替换:
- `store.state.` → `(store.state as UTSJSONObject)['`
- `ref(null as any)` → `ref<any | null>(null)`
- `item['`、`item["` → 改为 `getPkg(item, '`
2. 检查对象映射:有 `Record<number, ...>` 或数字 key 字面量 → 改成函数。
3. 检查数字展示:`toLocaleString`、`Number()` → 改成 `parseFloat().toString()`。
4. 检查 storage/JSON:直接 `JSON.parse` → 改成 `parseStorageJson`。
5. 检查 uni 扩展:`uni.$xxx` → 下标访问。
6. 检查 onShow/onLoad 中的组件 ref 方法调用 → 加 `setTimeout` + `callExposedMethod`。
7. 编译验证。
---
## 十三、参考文件
- Store 访问、dispatch、parseCustomerInfo:`store/index.uts`
- parseStorageJson:`api/system-api.uts`
- getPkg、callExposedMethod:`pages/boutique/index.uvue`
- 数字 key 映射:`components/HomeFrame/LeftSide.uvue` 中的 `getSceneTypeItem`
<template> <template>
<view class="page"> <view class="page">
<text>测试页面</text> <text class="title">测试页面</text>
<button class="btn" @click="runTest">运行 Store 测试 (V2)</button>
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { onLoad } from "@dcloudio/uni-app"; import { onLoad } from "@dcloudio/uni-app";
import { runStoreTest } from "../../test/test_store_v2.uts";
onLoad((options: OnLoadOptions) => { onLoad((options: OnLoadOptions) => {
console.log("测试页面加载"); console.log("测试页面加载");
}); });
const runTest = () => {
runStoreTest();
}
</script> </script>
<style> <style>
...@@ -17,7 +23,21 @@ onLoad((options: OnLoadOptions) => { ...@@ -17,7 +23,21 @@ onLoad((options: OnLoadOptions) => {
width: 750rpx; width: 750rpx;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
background-color: #f5f5f5;
}
.title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
}
.btn {
margin-top: 20px;
background-color: #007aff;
color: #ffffff;
padding: 10px 20px;
border-radius: 5px;
} }
</style> </style>
# uni-app x Store 模块使用说明
本目录包含 uni-app x 项目的状态管理实现。该方案基于 Vue 3 的 `reactive` 响应式系统,结合 **Class (类)** 定义状态结构,以满足 UTS 严格的类型系统要求,同时保持了与 Vuex 类似的 API (`state`, `getters`, `dispatch`, `commit`)。
## 目录结构
- **index.uts**: 核心 Store 文件。定义了全局 State 类 (`RootState`)、初始状态、Getters 以及 `dispatch`/`commit` 方法。
- **mapHelpers.uts**: 提供类似 Vuex 的辅助函数 (`mapState`, `mapGetters`, `mapMutations`),用于在 Options API 或 Vue 组件中简化状态访问。
- **modules/**: 独立的功能模块(如 `user.uts`, `audio.uts`),每个模块通过 **Class** 定义其状态结构。
## 核心概念与变更
### 1. State (状态) - 基于 Class
为了解决 UTS 中对象字面量 (`{}`) 与接口/类型 (`interface`/`type`) 之间的兼容性问题(如 "Classifier does not have a companion object" 错误),所有 State 现在都通过 **Class** 定义,并使用 `reactive(new StateClass())` 初始化。
**模块定义示例 (`store/modules/user.uts`)**:
```typescript
import { reactive } from "vue";
// 1. 定义 State 类 (必须包含 static _C 属性以规避编译错误)
export class UserStateType {
static _C: string = "companion"; // 必须存在,解决 UTS 伴生对象报错
token: string | null = null;
userInfo: UTSJSONObject = {};
isLoggedIn: boolean = false;
}
// 2. 初始化 State
export const state = reactive(new UserStateType());
// ... actions & getters
```
### 2. RootState (根状态)
`RootState` 在 `store/index.uts` 中定义为一个 **Class**,显式引用所有子模块的状态。
**`store/index.uts`**:
```typescript
import { state as userState, UserStateType } from "@/store/modules/user.uts";
// ... 其他模块导入
export class RootState {
user: UserStateType = userState;
// ... 其他模块属性
}
export const state = reactive(new RootState());
```
### 3. Actions & Mutations
Actions 中修改 State 时,由于 UTS 的类型检查,可能需要对 Payload 进行显式类型转换,或者避免使用对象展开运算符 (`...`) 直接赋值给 Class 实例。
**正确写法**:
```typescript
// store/modules/user.uts
export const actions = {
setUserInfo: (payload: any): any | null => {
// 显式转换类型
const data = payload as UTSJSONObject;
// 逐个属性赋值 (推荐,类型安全)
const s = state as UserStateType;
if (data['name'] != null) {
s.userInfo['name'] = data['name'];
}
// 或者整体赋值 (需确保类型匹配)
// (state as UserStateType).userInfo = data;
return null;
}
}
```
## 如何添加新模块
1. **创建模块文件**: 在 `store/modules/` 下创建 `xxx.uts`。
2. **定义 State 类**:
* 创建 `export class XxxStateType { static _C = "companion"; ... }`。
* 定义所有属性并赋予默认值。
3. **导出 State**: `export const state = reactive(new XxxStateType());`。
4. **注册模块 (`store/index.uts`)**:
* **顶部导入**:
```typescript
import { state as xxxState, XxxStateType } from "@/store/modules/xxx.uts";
import * as xxx from "@/store/modules/xxx.uts"; // 用于动态注册 actions
```
* **添加到 `modules` 数组**: `const modules: any[] = [..., xxx];`
* **添加到 `RootState` 类**:
```typescript
export class RootState {
// ...
xxx: XxxStateType = xxxState;
}
```
## 类型安全最佳实践
1. **避免对象字面量赋值给 Class**: 不要尝试使用 `{ ...state, ...newData } as StateType` 来更新状态,这在 UTS 中会导致类型丢失或运行时错误。请修改 Class 实例的具体属性。
2. **显式类型转换**: 在 Actions 中接收 `payload: any` 后,务必使用 `as Type` 将其转换为预期类型后再使用。
3. **处理 Nullable**: 注意 `storage.get()` 等方法返回的是 `Any?` (可空),在使用前可能需要 `as any` 或判空处理。
## 在组件中使用
### 直接导入 (推荐)
```typescript
import { state } from '@/store/index.uts'
// 读取
const token = state.user.token
// 写入 (通过 dispatch)
import { dispatch } from '@/store/index.uts'
dispatch('user/setToken', 'new-token')
```
### 使用 mapHelpers (Options API)
```typescript
import { mapState, mapGetters } from '@/store/mapHelpers.uts'
export default {
computed: {
...mapState(['user']),
...mapGetters(['token'])
}
}
```
...@@ -5,15 +5,15 @@ ...@@ -5,15 +5,15 @@
* import { mapState, mapGetters, mapMutations } from '@/store/mapHelpers.uts' * import { mapState, mapGetters, mapMutations } from '@/store/mapHelpers.uts'
* import store from '@/store/index.uts' * import store from '@/store/index.uts'
*/ */
import type { RootState } from './index.uts' import type { RootState } from "./index.uts";
/** 组件实例类型(含 $store) */ /** 组件实例类型(含 $store) */
type ComponentThis = { type ComponentThis = {
$store: { $store: {
state: RootState
getters: Record<string, any>
dispatch: (name: string, payload?: any) => void
commit: (type: string, payload?: any) => void commit: (type: string, payload?: any) => void
dispatch: (name: string, payload?: any) => void
getters: Record<string, any>
state: RootState
} }
} }
...@@ -29,35 +29,33 @@ export function mapState( ...@@ -29,35 +29,33 @@ export function mapState(
namespaceOrMap: string | string[], namespaceOrMap: string | string[],
map?: string[] map?: string[]
): Record<string, () => any> { ): Record<string, () => any> {
if (typeof namespaceOrMap == 'string' && map != null) { if (typeof namespaceOrMap === "string" && map != null) {
// mapState('audio', ['isEnd','isStart']) // mapState('audio', ['isEnd','isStart'])
const ns = namespaceOrMap const ns = namespaceOrMap;
const result: Record<string, () => any> = {} const result: Record<string, () => any> = {};
for (let i = 0; i < map.length; i++) { for (const key of map) {
const key = map[i]
result[key] = function (this: ComponentThis): any { result[key] = function (this: ComponentThis): any {
const moduleState = (this.$store.state as any)[ns] const moduleState = (this.$store.state as any)[ns];
return moduleState != null ? moduleState[key] : null return moduleState != null ? moduleState[key] : null;
};
} }
} return result;
return result
} }
// mapState(['user','point.tabIndex']) // mapState(['user','point.tabIndex'])
const keys = namespaceOrMap as string[] const keys = namespaceOrMap as string[];
const result: Record<string, () => any> = {} const result: Record<string, () => any> = {};
for (let i = 0; i < keys.length; i++) { for (const path of keys) {
const path = keys[i] const localKey = path.includes(".") ? path : path;
const localKey = path.includes('.') ? path : path
result[localKey] = function (this: ComponentThis): any { result[localKey] = function (this: ComponentThis): any {
const parts = path.split('.') const parts = path.split(".");
let v: any = this.$store.state let v: any = this.$store.state;
for (let j = 0; j < parts.length; j++) { for (const part of parts) {
v = v != null ? v[parts[j]] : null v = v != null ? v[part] : null;
}
return v
} }
return v;
};
} }
return result return result;
} }
/** /**
...@@ -65,17 +63,16 @@ export function mapState( ...@@ -65,17 +63,16 @@ export function mapState(
* mapGetters(['customerInfo','receptionStatus']) * mapGetters(['customerInfo','receptionStatus'])
*/ */
export function mapGetters(keys: string[]): Record<string, () => any> { export function mapGetters(keys: string[]): Record<string, () => any> {
const result: Record<string, () => any> = {} const result: Record<string, () => any> = {};
for (let i = 0; i < keys.length; i++) { for (const key of keys) {
const key = keys[i]
result[key] = function (this: ComponentThis): any { result[key] = function (this: ComponentThis): any {
const g = this.$store.getters as Record<string, any> const g = this.$store.getters as Record<string, any>;
if (g == null || typeof g[key] == 'undefined') return null if (g == null || g[key] === undefined) return null;
const v = g[key] const v = g[key];
return typeof v == 'function' ? v() : v return typeof v === "function" ? v() : v;
} };
} }
return result return result;
} }
/** /**
...@@ -92,26 +89,24 @@ export function mapMutations( ...@@ -92,26 +89,24 @@ export function mapMutations(
namespaceOrMap: string | string[], namespaceOrMap: string | string[],
map?: string[] map?: string[]
): Record<string, (payload?: any) => void> { ): Record<string, (payload?: any) => void> {
if (typeof namespaceOrMap == 'string' && map != null) { if (typeof namespaceOrMap === "string" && map != null) {
const ns = namespaceOrMap const ns = namespaceOrMap;
const result: Record<string, (payload?: any) => void> = {} const result: Record<string, (payload?: any) => void> = {};
for (let i = 0; i < map.length; i++) { for (const key of map) {
const key = map[i]
result[key] = function (this: ComponentThis, payload?: any): void { result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.commit(`${ns}/${key}`, payload) this.$store.commit(`${ns}/${key}`, payload);
};
} }
return result;
} }
return result const keys = namespaceOrMap as string[];
} const result: Record<string, (payload?: any) => void> = {};
const keys = namespaceOrMap as string[] for (const key of keys) {
const result: Record<string, (payload?: any) => void> = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
result[key] = function (this: ComponentThis, payload?: any): void { result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.commit(key, payload) this.$store.commit(key, payload);
} };
} }
return result return result;
} }
/** /**
...@@ -119,12 +114,11 @@ export function mapMutations( ...@@ -119,12 +114,11 @@ export function mapMutations(
* mapActions(['setCustomerInfo','clearHistory']) * mapActions(['setCustomerInfo','clearHistory'])
*/ */
export function mapActions(keys: string[]): Record<string, (payload?: any) => void> { export function mapActions(keys: string[]): Record<string, (payload?: any) => void> {
const result: Record<string, (payload?: any) => void> = {} const result: Record<string, (payload?: any) => void> = {};
for (let i = 0; i < keys.length; i++) { for (const key of keys) {
const key = keys[i]
result[key] = function (this: ComponentThis, payload?: any): void { result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.dispatch(key, payload) this.$store.dispatch(key, payload);
} };
} }
return result return result;
} }
import { reactive } from "vue";
const _emptyArr: any[] = [] as any[];
export class AudioInfoType {
static _C: string = "companion";
audioStatus: string = "";
endReasonType: number = 0;
receptionEndTime: string = "";
receptionStartTime: string = "";
}
export class AudioStateType {
static _C: string = "companion";
audioInfo: AudioInfoType = new AudioInfoType();
audioList: any[] = [];
booksList: any[] = [];
endReasonType: number = 0;
perRecordNumber: number = 0;
receptionStatus: string = "";
}
function formatDateTime(d: Date, sep: string): string {
const y = d.getFullYear();
const m = (`0${ d.getMonth() + 1}`).slice(-2);
const day = (`0${ d.getDate()}`).slice(-2);
const h = (`0${ d.getHours()}`).slice(-2);
const min = (`0${ d.getMinutes()}`).slice(-2);
const s = (`0${ d.getSeconds()}`).slice(-2);
return `${y}${sep}${m}${sep}${day} ${h}:${min}:${s}`;
}
export const state = reactive(new AudioStateType());
export const getters = {
receptionStatus: (): any => (state as AudioStateType).receptionStatus,
booksList: (): any => (state as AudioStateType).booksList
};
export const actions = {
setReceptionStatus: (payload: any): any | null => {
(state as AudioStateType).receptionStatus = (payload != null ? payload : "") as string;
return null;
},
setBooks: (payload: any): any | null => {
(state as AudioStateType).booksList = (payload != null ? payload : _emptyArr) as any[];
return null;
},
setPerRecordNumber: (payload: any): any | null => {
(state as AudioStateType).perRecordNumber = (payload != null ? payload : 0) as number;
return null;
},
setAudioList: (payload: any): any | null => {
(state as AudioStateType).audioList = (payload != null ? payload : _emptyArr) as any[];
return null;
},
setAudioInfo: (payload: any): any | null => {
const data = (payload != null ? payload : {}) as UTSJSONObject;
if (data.audioStatus == "start") {
data.receptionStartTime = formatDateTime(new Date(), "/");
data.receptionEndTime = "";
}
if (data.audioStatus == "end") {
data.receptionEndTime = formatDateTime(new Date(), "/");
}
const s = state as AudioStateType;
const info = s.audioInfo;
const audioStatus = data.audioStatus;
if (audioStatus != null) {
info.audioStatus = audioStatus as string;
}
const endReasonType = data.endReasonType;
if (endReasonType != null) {
info.endReasonType = endReasonType as number;
}
const receptionStartTime = data.receptionStartTime;
if (receptionStartTime != null) {
info.receptionStartTime = receptionStartTime as string;
}
const receptionEndTime = data.receptionEndTime;
if (receptionEndTime != null) {
info.receptionEndTime = receptionEndTime as string;
}
return null;
}
};
import { reactive } from "vue";
export class BoutiqueStateType {
static _C: string = "companion";
baseConfigData: UTSJSONObject = {};
}
export const state = reactive(new BoutiqueStateType());
export const getters = {};
export const actions = {
setBoutiqueBaseConfig: (payload: any): any | null => {
(state as BoutiqueStateType).baseConfigData = (payload != null ? payload : {}) as UTSJSONObject;
return {};
}
};
import { reactive } from "vue";
export class PointStateType {
static _C: string = "companion";
tabIndex: any = 0;
}
export const state = reactive(new PointStateType());
export const getters = {};
export const actions = {
setTab: (payload: any): any | null => {
(state as PointStateType).tabIndex = payload != null ? payload : 0;
return null;
}
};
import { reactive } from 'vue' import { reactive } from "vue";
export type ReceptionState = { export type ReceptionState = {
customerKey: string
customerInfo: UTSJSONObject | null
receptionStatus: string
booksList: UTSJSONObject[] booksList: UTSJSONObject[]
customerInfo: null | UTSJSONObject
customerKey: string
receptionKey: string receptionKey: string
receptionStatus: string
receptionTrack: UTSJSONObject[] receptionTrack: UTSJSONObject[]
} }
// 模块状态 // 模块状态
export const receptionState = reactive({ export const receptionState = reactive({
customerKey: '', customerKey: "",
customerInfo: null, customerInfo: null,
receptionStatus: '', receptionStatus: "",
booksList: [], booksList: [],
receptionKey: '', receptionKey: "",
receptionTrack: [] receptionTrack: []
} as ReceptionState) } as ReceptionState);
// 模块变更方法 (Mutations) // 模块变更方法 (Mutations)
export const setCustomerKey = (payload: string) => { export const setCustomerKey = (payload: string) => {
receptionState.customerKey = payload receptionState.customerKey = payload;
} };
export const setCustomerInfo = (payload: UTSJSONObject | null) => { export const setCustomerInfo = (payload: null | UTSJSONObject) => {
receptionState.customerInfo = payload receptionState.customerInfo = payload;
} };
export const setReceptionStatus = (payload: string) => { export const setReceptionStatus = (payload: string) => {
receptionState.receptionStatus = payload receptionState.receptionStatus = payload;
} };
export const setBookList = (payload: UTSJSONObject[]) => { export const setBookList = (payload: UTSJSONObject[]) => {
receptionState.booksList = payload receptionState.booksList = payload;
} };
export const setReceptionKey = (payload: string) => { export const setReceptionKey = (payload: string) => {
receptionState.receptionKey = payload receptionState.receptionKey = payload;
} };
export const setReceptionTrack = (payload: UTSJSONObject[]) => { export const setReceptionTrack = (payload: UTSJSONObject[]) => {
receptionState.receptionTrack = payload receptionState.receptionTrack = payload;
} };
import { reactive } from "vue";
export class SysStateType {
static _C: string = "companion";
activityWindowPopStatus: any = 0;
isInBackground: boolean = false;
}
export const state = reactive(new SysStateType());
export const getters = {
isInBackground: (): boolean => (state as SysStateType).isInBackground,
activityWindowPopStatus: (): any => (state as SysStateType).activityWindowPopStatus
};
export const actions = {
setBackgroundState: (payload: any): any | null => {
(state as SysStateType).isInBackground = payload != null && payload != false;
return null;
},
setActivityWindowPopCount: (payload: any): any | null => {
(state as SysStateType).activityWindowPopStatus = payload != null ? payload : 0;
return null;
}
};
import { reactive } from "vue";
export class UpdateStateType {
static _C: string = "companion";
status: boolean = false;
}
export const state = reactive(new UpdateStateType());
export const getters = {};
export const actions = {
openUpdateModal: (payload: any): any | null => {
(state as UpdateStateType).status = true;
return null;
}
};
import { reactive } from "vue";
import { storage } from "@/utils/storage.uts";
// ============ 默认值 ============
const _emptyArr: any[] = [] as any[];
const defaultCustomerInfo = {
customerName: "",
carBrand: "",
carModel: "",
phoneNumber: "",
salesUuid: "",
staffName: "",
newCarFare: "",
carModelId: "",
carBuyers: "",
carPurchaseMethod: "",
oneCarBrand: "",
oneCarBrandId: ""
};
function parseCustomerInfo(raw: any): UTSJSONObject {
if (raw === null) return defaultCustomerInfo as UTSJSONObject;
if (typeof raw === "string") {
if (raw === "") return defaultCustomerInfo as UTSJSONObject;
try {
const parsed = JSON.parse(raw) as UTSJSONObject;
return { ...defaultCustomerInfo, ...parsed } as UTSJSONObject;
} catch {
return defaultCustomerInfo as UTSJSONObject;
}
}
return { ...defaultCustomerInfo, ...(raw as UTSJSONObject) } as UTSJSONObject;
}
// ============ State 类型 ============
export class UserStateType {
static _C: string = "companion";
boutiqueCarList: any[] = [];
boutiqueDefaultCarBrandId: string = "";
boutiqueMediaConfig: Record<string, any> = {} as Record<string, any>;
carBrands: any[] = [];
currentCarInfo: Record<string, any> = {} as Record<string, any>;
customerInfo: UTSJSONObject = parseCustomerInfo(storage.get("customerInfo") as any);
customerKey: number = Date.now();
defaultCarId: string = "";
employeeList: any[] = [];
haveCustomerAccess: boolean = true;
historyStatus: number = Date.now();
paymentType: any[] = [];
receptionKey: number = Date.now();
receptionTrack: Record<string, any> = {} as Record<string, any>;
token: any | null = null;
userData: any | null = null;
viewKey: number = Date.now();
}
type ReceptionTrackPayload = { key: string; value: any }
// ============ 初始化 State ============
const savedCustomerInfo = storage.get("customerInfo");
const initialCustomerInfo = parseCustomerInfo(savedCustomerInfo as any);
export const state = reactive(new UserStateType());
// ============ Getters ============
export const getters = {
token: (): any | null => (state as UserStateType).token,
userData: (): any | null => (state as UserStateType).userData,
userId: (): any | null => {
const ud = (state as UserStateType).userData;
return (ud != null ? (ud as UTSJSONObject).id : null) as any;
},
customerInfo: (): UTSJSONObject => (state as UserStateType).customerInfo,
receptionTrack: (): Record<string, any> => (state as UserStateType).receptionTrack,
receptionKey: (): number => (state as UserStateType).receptionKey,
customerKey: (): number => (state as UserStateType).customerKey
};
// ============ Actions ============
export const actions = {
setCustomerInfo: (payload: any): any | null => {
const data = (payload != null ? payload : {}) as UTSJSONObject;
storage.set("customerInfo", JSON.stringify(data), 0);
(state as UserStateType).customerInfo = { ...defaultCustomerInfo, ...data } as UTSJSONObject;
(state as UserStateType).customerKey = Date.now();
return null;
},
clearCustomerInfo: (payload: any): any | null => {
storage.set("customerInfo", JSON.stringify(defaultCustomerInfo), 0);
(state as UserStateType).customerInfo = { ...defaultCustomerInfo } as UTSJSONObject;
(state as UserStateType).customerKey = Date.now();
return null;
},
clearHistory: (payload: any): any | null => {
(state as UserStateType).historyStatus = Date.now();
return null;
},
setPaymentType: (payload: any): any | null => {
(state as UserStateType).paymentType = (payload != null ? payload : _emptyArr) as any[];
return null;
},
setCarBrandsList: (payload: any): any | null => {
(state as UserStateType).carBrands = (payload != null ? payload : _emptyArr) as any[];
return null;
},
setEmployeeList: (payload: any): any | null => {
(state as UserStateType).employeeList = (payload != null ? payload : _emptyArr) as any[];
return null;
},
setReceptionTrack: (payload: any): any | null => {
const p = payload as ReceptionTrackPayload;
if (p != null && p.key != null) {
(state as UserStateType).receptionTrack[p.key] = p.value;
}
(state as UserStateType).receptionKey = Date.now();
return null;
},
clearReceptionTrack: (payload: any): any | null => {
(state as UserStateType).receptionTrack = {} as Record<string, any>;
(state as UserStateType).receptionKey = Date.now();
return null;
},
updateViewKey: (payload: any): any | null => {
(state as UserStateType).viewKey = Date.now();
return null;
},
setCurrentCarInfo: (payload: any): any | null => {
(state as UserStateType).currentCarInfo = (payload != null ? payload : {}) as Record<string, any>;
return null;
},
getCustomerInfo: (payload: any): any | null => {
return (state as UserStateType).customerInfo;
}
};
import { watch } from "vue";
import { state as rawState, store } from "@/store/index.uts";
import { AudioStateType } from "@/store/modules/audio.uts";
import { UserStateType } from "@/store/modules/user.uts";
export function runStoreTest() {
console.log("=== 开始 Store 测试 (V2) ===");
// 1. 基础对象获取
// store 在 UTS 中作为导入对象,视为 UTSJSONObject
const storeObj = store as UTSJSONObject;
const getters = storeObj.getters as UTSJSONObject;
// Access state directly (Strong Typed) to avoid ClassCastException
// rawState is RootStateReactiveObject
const state = rawState;
// Cast to UserState explicitly as rawState.user might be reactive proxy
const userState = state.user as UserStateType;
// 2. 初始状态检查
// getters["key"] 返回 Any?,强制转换为函数类型
const customerInfoGetter = getters.customerInfo as () => UTSJSONObject;
const initCustomerInfo = customerInfoGetter();
console.log(`初始 customerInfo: ${JSON.stringify(initCustomerInfo)}`);
// 3. 设置监听器
// userState.customerInfo is UTSJSONObject
const stopWatch = watch(
(): UTSJSONObject => userState.customerInfo,
(newVal: UTSJSONObject, oldVal: UTSJSONObject) => {
console.log(`[Watch] customerInfo 发生变化: ${JSON.stringify(newVal)}`);
},
{ deep: true }
);
// 4. 执行 Commit
console.log("执行 commit('setCustomerInfo', { customerName: '测试用户' })...");
const commitFn = storeObj.commit as (type: string, payload: any) => void;
commitFn("setCustomerInfo", { customerName: "测试用户" });
// 5. 验证状态
const newCustomerInfo = userState.customerInfo;
// newCustomerInfo is UTSJSONObject, use bracket access
const pass1 = newCustomerInfo.customerName == "测试用户";
console.log(`验证 State 更新: ${pass1 ? "PASS" : "FAIL"} (期望: '测试用户', 实际: '${newCustomerInfo.customerName}')`);
// 6. 验证 Getter
const getterVal = customerInfoGetter();
const pass2 = getterVal.customerName == "测试用户";
console.log(`验证 Getter 获取: ${pass2 ? "PASS" : "FAIL"} (期望: '测试用户', 实际: '${getterVal.customerName}')`);
// 7. 测试 Dispatch
console.log("执行 dispatch('setReceptionStatus', 'recording')...");
const dispatchFn = storeObj.dispatch as (action: string, payload: any) => any | null;
dispatchFn("setReceptionStatus", "recording");
// Cast to AudioState explicitly
const audioState = state.audio as AudioStateType;
const status = audioState.receptionStatus;
const pass3 = status == "recording";
console.log(`验证 Audio State 更新: ${pass3 ? "PASS" : "FAIL"} (期望: 'recording', 实际: '${status}')`);
// 8. 清理
stopWatch();
// 恢复状态
commitFn("clearCustomerInfo", {});
dispatchFn("setReceptionStatus", "");
console.log("=== Store 测试结束 ===");
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!