Commit bb8d8aa7 by liimin

refactor(store): 迁移项目至x-pinia-s状态管理

引入x-pinia-s uni模块作为uni-app-x的状态管理实现,替换原有的自定义Vuex风格store系统。
新增x-pinia-s uni模块的全部依赖文件与配置。
删除旧的冗余store模块文件。
重构全项目的store调用逻辑,替换为Pinia标准的useStore写法。
更新全局注入配置,将原有的$store改为$pinia并挂载到Vue实例。
修复客户信息、车型的字段展示兼容问题,兼容新旧字段命名。
调整录音服务的数据库表结构与业务字段定义,适配新业务需求。
更新测试文件适配新的状态管理系统。
1 parent c6a99b7e
Showing 53 changed files with 1436 additions and 1071 deletions
...@@ -51,7 +51,6 @@ ...@@ -51,7 +51,6 @@
import { computed, onUnmounted, ref, watch } from "vue"; import { computed, onUnmounted, ref, watch } from "vue";
import { getCarBrandsListApi, getMerchantCarBrandList } from "@/api/common-api.uts"; import { getCarBrandsListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { recordService } from "@/services/recorder/index.uts"; import { recordService } from "@/services/recorder/index.uts";
import { dispatchRecordCarSelectLinkage, dispatchSetCarBrandsList, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { useWindowHeight } from "@/services/adapter/hooks/index.uts"; import { useWindowHeight } from "@/services/adapter/hooks/index.uts";
import { type RecordData } from "@/services/recorder/types/record.uts"; import { type RecordData } from "@/services/recorder/types/record.uts";
...@@ -104,16 +103,7 @@ const currentCarList = ref<Array<any>>([]); ...@@ -104,16 +103,7 @@ const currentCarList = ref<Array<any>>([]);
const dynamicZIndex = computed<number>(() => { const dynamicZIndex = computed<number>(() => {
return 10090 + (currentView.value == "series" ? 1 : 0); return 10090 + (currentView.value == "series" ? 1 : 0);
}); });
const watchStatus = computed<boolean>(() => { const watchStatus = ref<boolean>(false);
const status = state.user?.historyStatus;
if (status == null) {
return false;
} else if (status == 1) {
return true;
} else {
return false;
}
});
const carModel = computed<null|string>(() => { const carModel = computed<null|string>(() => {
const car_key = props.carModelKey; const car_key = props.carModelKey;
if (props.customBoolean) { if (props.customBoolean) {
...@@ -121,7 +111,7 @@ const carModel = computed<null|string>(() => { ...@@ -121,7 +111,7 @@ const carModel = computed<null|string>(() => {
const value = echoObj[car_key]; const value = echoObj[car_key];
return value != null ? `${value}` : null; return value != null ? `${value}` : null;
} else { } else {
return `${state.user.customerInfo.carModel}`; return null;
} }
}); });
const carBrand = computed<null|string>(() => { const carBrand = computed<null|string>(() => {
...@@ -131,15 +121,14 @@ const carBrand = computed<null|string>(() => { ...@@ -131,15 +121,14 @@ const carBrand = computed<null|string>(() => {
const value = echoObj[car_key]; const value = echoObj[car_key];
return value != null ? `${value}` : null; return value != null ? `${value}` : null;
} else { } else {
return `${state.user.customerInfo.carBrand}`; return null;
} }
}); });
const boutiqueDefaultCarBrandId = computed<any>(() => { const boutiqueDefaultCarBrandId = computed<any>(() => {
return state.user.boutiqueDefaultCarBrandId; return '1';
}); });
const defaultCarId = computed<any>(() => { const defaultCarId = computed<any>(() => {
const val = state.user.defaultCarId; return "";
return val != null && val != 0 ? val : "";
}); });
// 是否显示返回按钮(车系视图时显示) // 是否显示返回按钮(车系视图时显示)
const showBackButton = computed<boolean>(() => { const showBackButton = computed<boolean>(() => {
...@@ -173,39 +162,20 @@ function handleBackClick(): void { ...@@ -173,39 +162,20 @@ function handleBackClick(): void {
} }
function handleSelect(item: any): void { function handleSelect(item: any): void {
const selectItemVal = selectItem.value; const selectItemVal = selectItem.value;
const stateCustomerInfo = state.user.customerInfo;
// const customerInfo: UTSJSONObject = {
// ...state.user.customerInfo,
// carBrand: selectItemVal.carChildsBrandName,
// carBrandId: selectItemVal.carChildsBrandId,
// oneCarBrand: selectItemVal.carBrand,
// oneCarBrandId: selectItemVal.carBrandId,
// carModel: item.name,
// carModelId: item.id
// }
stateCustomerInfo.carBrand = selectItemVal.carChildsBrandName;
stateCustomerInfo.carBrandId = selectItemVal.carChildsBrandId;
stateCustomerInfo.oneCarBrand = selectItemVal.carBrand;
stateCustomerInfo.oneCarBrandId = selectItemVal.carBrandId;
stateCustomerInfo.carModel = (item as UTSJSONObject).name;
stateCustomerInfo.carModelId = (item as UTSJSONObject).id;
if (props.linkage) { if (props.linkage) {
const itemObj = item as UTSJSONObject;
const businessData: RecordData = { const businessData: RecordData = {
// carBrand: selectItemVal.carChildsBrandName, brandId: selectItemVal['carChildsBrandId'] != null ? `${selectItemVal['carChildsBrandId']}` : "",
// carBrandId: selectItemVal.carChildsBrandId, brandName: selectItemVal['carChildsBrandName'] != null ? `${selectItemVal['carChildsBrandName']}` : "",
// oneCarBrand: selectItemVal.carBrand, seriesId: itemObj['id'] != null ? `${itemObj['id']}` : "",
// oneCarBrandId: selectItemVal.carBrandId, seriesName: itemObj['name'] != null ? `${itemObj['name']}` : ""
// carModel: (item as UTSJSONObject).name,
// carModelId: (item as UTSJSONObject).id
carType:""
} as RecordData; } as RecordData;
recordService.updateBusinessData(businessData); recordService.updateBusinessData(businessData);
// uvue 里直接传字符串字面量给 dispatch 会触发 Android kotlin/java String 桥接编译问题
dispatchRecordCarSelectLinkage(selectItemVal);
} }
// 关闭弹窗并发出选择事件 // 关闭弹窗并发出选择事件
visible.value = false; visible.value = false;
emit("select", { ...item, ...selectItemVal }); const merged = { ...(item as UTSJSONObject), ...(selectItemVal as UTSJSONObject) } as UTSJSONObject;
emit("select", merged);
} }
// 选择品牌(切换到车系视图) // 选择品牌(切换到车系视图)
function selectBrand(item: any, index: number): void { function selectBrand(item: any, index: number): void {
...@@ -351,7 +321,6 @@ function open(): void { ...@@ -351,7 +321,6 @@ function open(): void {
} }
}); });
} }
dispatchSetCarBrandsList(carBrandListData);
storage.set(STORAGE_KEY_CAR_BRAND_LIST, carBrandListData, 0); storage.set(STORAGE_KEY_CAR_BRAND_LIST, carBrandListData, 0);
} }
updateView.value = Date.now(); updateView.value = Date.now();
......
...@@ -41,7 +41,6 @@ import { ComponentPublicInstance, computed, onUnmounted, ref, watch } from "vue" ...@@ -41,7 +41,6 @@ import { ComponentPublicInstance, computed, onUnmounted, ref, watch } from "vue"
import { getEmployeeListApi } from "@/api/common-api.uts"; import { getEmployeeListApi } from "@/api/common-api.uts";
// import { resolutionState } from "@/services/adapter/index.uts"; // import { resolutionState } from "@/services/adapter/index.uts";
import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { useWindowHeight } from "@/services/adapter/hooks/index.uts"; import { useWindowHeight } from "@/services/adapter/hooks/index.uts";
...@@ -68,23 +67,12 @@ onUnmounted((): void => { ...@@ -68,23 +67,12 @@ onUnmounted((): void => {
const visible = ref<boolean>(false); const visible = ref<boolean>(false);
const watchStatus = computed<boolean>(() => { const watchStatus = ref<boolean>(false);
const status = state.user?.historyStatus;
if (status == null) {
return false;
} else if (status == 1) {
return true;
} else {
return false;
}
});
const updateView = ref<number>(Date.now()); const updateView = ref<number>(Date.now());
const salesUuid = computed<string>(() => { const salesUuid = computed<string>(() => {
const val1 = state.user.customerInfo.salesUuid; return props.salesPropsUuid;
const val2 = props.salesPropsUuid;
return val1 !== null && val1 !== "" ? (val1 as string) : val2;
}); });
// 动态计算 z-index,确保始终在最上层(高于 ToolBox 的 10073) // 动态计算 z-index,确保始终在最上层(高于 ToolBox 的 10073)
const dynamicZIndex = computed<number>(() => { const dynamicZIndex = computed<number>(() => {
...@@ -169,7 +157,6 @@ function open(): void { ...@@ -169,7 +157,6 @@ function open(): void {
console.log("getEmployeeListApi response:", res); console.log("getEmployeeListApi response:", res);
const list = res as Array<any>; const list = res as Array<any>;
console.log("list length:", list != null ? list.length : 0); console.log("list length:", list != null ? list.length : 0);
dispatch("setEmployeeList", list);
const listToStore = list != null ? list : []; const listToStore = list != null ? list : [];
console.log("Saving to storage, length:", listToStore.length); console.log("Saving to storage, length:", listToStore.length);
storage.set(STORAGE_KEY_EMPLOYEE_LIST, listToStore, 0); storage.set(STORAGE_KEY_EMPLOYEE_LIST, listToStore, 0);
......
...@@ -149,7 +149,6 @@ import { ComponentPublicInstance, computed, onMounted, onUnmounted, ref, watch } ...@@ -149,7 +149,6 @@ import { ComponentPublicInstance, computed, onMounted, onUnmounted, ref, watch }
import CarBrands from "@/components/CarBrands.uvue"; import CarBrands from "@/components/CarBrands.uvue";
import Employee from "@/components/Employee.uvue"; import Employee from "@/components/Employee.uvue";
import { recordService } from "@/services/recorder/index.uts"; import { recordService } from "@/services/recorder/index.uts";
import { state } from "@/store/index.uts";
import { type RecordData } from "@/services/recorder/types/record.uts"; import { type RecordData } from "@/services/recorder/types/record.uts";
import { toObj } from "@/utils/common.uts"; import { toObj } from "@/utils/common.uts";
...@@ -196,9 +195,9 @@ onUnmounted((): void => { ...@@ -196,9 +195,9 @@ onUnmounted((): void => {
const showPopup = ref<boolean>(false); // 控制弹窗显示(现在由 MessageBox 管理) const showPopup = ref<boolean>(false); // 控制弹窗显示(现在由 MessageBox 管理)
const formData = ref<UTSJSONObject>({ const formData = ref<UTSJSONObject>({
customerName: "", customerName: "",
customerPhone: "", customerMobile: "",
customerType: "", customerType: "",
carType: "", seriesName: "",
carModel: "", carModel: "",
phoneNumber: "", phoneNumber: "",
staffName: "" staffName: ""
...@@ -265,7 +264,7 @@ const FORM_OBJECT_MAIN: Array<FormObjectItem> = [ ...@@ -265,7 +264,7 @@ const FORM_OBJECT_MAIN: Array<FormObjectItem> = [
}, },
{ {
label: "客户电话", label: "客户电话",
key: "customerPhone", key: "customerMobile",
type: "input", type: "input",
inputType: "tel", inputType: "tel",
maxlength: 11, maxlength: 11,
...@@ -281,7 +280,7 @@ const FORM_OBJECT_MAIN: Array<FormObjectItem> = [ ...@@ -281,7 +280,7 @@ const FORM_OBJECT_MAIN: Array<FormObjectItem> = [
}, },
{ {
label: "品牌车型", label: "品牌车型",
key: "carType", key: "seriesName",
type: "input", type: "input",
inputType: "text", inputType: "text",
maxlength: 50, maxlength: 50,
...@@ -354,16 +353,7 @@ const showSuccess = (): void => { ...@@ -354,16 +353,7 @@ const showSuccess = (): void => {
}; };
// ============ 计算属性 ============ // ============ 计算属性 ============
const watchStatus = computed(() => { const watchStatus = ref<boolean>(false);
const status = state.user?.historyStatus;
if (status == null) {
return false;
} else if (status == 1) {
return true;
} else {
return false;
}
});
const tipsText = computed(() => { const tipsText = computed(() => {
const _sceneType = props.sceneType; const _sceneType = props.sceneType;
...@@ -538,7 +528,7 @@ const open = (): void => { ...@@ -538,7 +528,7 @@ const open = (): void => {
let stepValue = 1; let stepValue = 1;
// 检查必填字段 // 检查必填字段
const keys = ["customerName", "carType", "customerPhone", "customerType"]; const keys = ["customerName", "seriesName", "customerMobile", "customerType"];
for (const key of keys) { for (const key of keys) {
const value = formData.value[key] as null | string; const value = formData.value[key] as null | string;
if (value == null || value == "") { if (value == null || value == "") {
......
...@@ -41,7 +41,6 @@ ...@@ -41,7 +41,6 @@
<script setup lang="uts"> <script setup lang="uts">
import zoomPan from './zoom-pan.uvue' import zoomPan from './zoom-pan.uvue'
import { state } from "@/store/index.uts"
type HistoryItemStyle = { type HistoryItemStyle = {
color: string color: string
...@@ -114,16 +113,7 @@ ...@@ -114,16 +113,7 @@
const begin = ref<boolean>(false) const begin = ref<boolean>(false)
const isUnderBkg = ref<boolean>(false) const isUnderBkg = ref<boolean>(false)
const watchStatus = computed(() => { const watchStatus = ref<boolean>(false)
const status = state.user?.historyStatus
if (status == null) {
return false
} else if (status == 1) {
return true
} else {
return false
}
})
function onScale(e: number): void { function onScale(e: number): void {
scaleValue.value = e scaleValue.value = e
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
<script setup lang="uts"> <script setup lang="uts">
import { throttle } from '@/utils/common.uts' import { throttle } from '@/utils/common.uts'
import { state } from "@/store/index.uts"
type Point = { type Point = {
x: number x: number
...@@ -75,16 +74,7 @@ type TouchEvent = { ...@@ -75,16 +74,7 @@ type TouchEvent = {
} }
}) })
const watchStatus = computed(() => { const watchStatus = ref<boolean>(false)
const status = state.user?.historyStatus
if (status == null) {
return false
} else if (status == 1) {
return true
} else {
return false
}
})
watch(watchStatus.value , () => { watch(watchStatus.value , () => {
if (scale.value != 1) { if (scale.value != 1) {
......
...@@ -5,6 +5,7 @@ import { createSSRApp } from "vue"; ...@@ -5,6 +5,7 @@ import { createSSRApp } from "vue";
import { logger } from "@/services/logger"; import { logger } from "@/services/logger";
import DBRecord from "@/services/recorder/DBRecord.uts"; import DBRecord from "@/services/recorder/DBRecord.uts";
import { RecordService } from "@/services/recorder/RecordService.uts"; import { RecordService } from "@/services/recorder/RecordService.uts";
import { pinia } from "@/store/index.uts";
import App from "./App.uvue"; import App from "./App.uvue";
import { appMixin } from "./utilsApi"; import { appMixin } from "./utilsApi";
...@@ -12,6 +13,7 @@ import { appMixin } from "./utilsApi"; ...@@ -12,6 +13,7 @@ import { appMixin } from "./utilsApi";
export function createApp() { export function createApp() {
const app = createSSRApp(App); const app = createSSRApp(App);
app.use(pinia);
// 挂载日志模块到 uni.$log,之后可以直接使用 uni.$log.info() // 挂载日志模块到 uni.$log,之后可以直接使用 uni.$log.info()
// logger.mount(); // logger.mount();
// 挂载录音服务到 uni.$recordService,之后可以直接使用 uni.$recordService // 挂载录音服务到 uni.$recordService,之后可以直接使用 uni.$recordService
......
import { computed, ref, type ComputedRef, type Ref } from "vue"; import { computed, ref, type ComputedRef, type Ref } from "vue";
import { getContents } from "@/api/modules/contents.uts"; import { getContents } from "@/api/modules/contents.uts";
import { dispatch } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
const _emptyArr: any[] = [] as any[]; const _emptyArr: any[] = [] as any[];
...@@ -110,9 +110,6 @@ export function useBoutiqueLogic(): BoutiqueLogic { ...@@ -110,9 +110,6 @@ export function useBoutiqueLogic(): BoutiqueLogic {
}; };
const clearHistory = (): void => { const clearHistory = (): void => {
dispatch("clearCustomerInfo");
dispatch("clearHistory");
dispatch("clearReceptionTrack");
}; };
const jumpPage = (_homeFrameRef: any, pid: string): void => { const jumpPage = (_homeFrameRef: any, pid: string): void => {
......
...@@ -34,7 +34,7 @@ import { UnSwiperItem } from "@/types/uview-unix-types.uts"; ...@@ -34,7 +34,7 @@ import { UnSwiperItem } from "@/types/uview-unix-types.uts";
import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList } from "@/api/common-api.uts"; import { getCarBrandsListApi, getEmployeeListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { getMockData, getSoureData } from "@/api/system-api.uts"; import { getMockData, getSoureData } from "@/api/system-api.uts";
import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { delay } from "@/utils/delay.uts"; import { delay } from "@/utils/delay.uts";
import ProductIntroSwiper from "@/components/ProductIntroSwiper.uvue"; import ProductIntroSwiper from "@/components/ProductIntroSwiper.uvue";
...@@ -330,7 +330,6 @@ function get_Vehicle_Sales_Data(): void { ...@@ -330,7 +330,6 @@ function get_Vehicle_Sales_Data(): void {
brandIdList.push(idStr); brandIdList.push(idStr);
}); });
getSoure(brandIdList, subBrandIdList); getSoure(brandIdList, subBrandIdList);
dispatch("setCarBrandsList", carBrandList);
storage.set("carBrandList", carBrandList, 0); storage.set("carBrandList", carBrandList, 0);
if (carBrandList.length > 0) { if (carBrandList.length > 0) {
const index = 0; const index = 0;
...@@ -341,7 +340,6 @@ function get_Vehicle_Sales_Data(): void { ...@@ -341,7 +340,6 @@ function get_Vehicle_Sales_Data(): void {
getEmployeeListApi({ getEmployeeListApi({
merchantId: shopMerchantId merchantId: shopMerchantId
}).then(res => { }).then(res => {
dispatch("setEmployeeList", res);
storage.set("employeeList", res, 0); storage.set("employeeList", res, 0);
}); });
} }
...@@ -353,10 +351,7 @@ function initEquityData(): void { ...@@ -353,10 +351,7 @@ function initEquityData(): void {
const mockDataObj = mockdata as UTSJSONObject; const mockDataObj = mockdata as UTSJSONObject;
const channelType = userInfo.channelType as number; const channelType = userInfo.channelType as number;
if (channelType == 1 && mockDataObj.boutiqueDefaultCarBrandId != null) { if (channelType == 1 && mockDataObj.boutiqueDefaultCarBrandId != null) {
state.user.boutiqueDefaultCarBrandId = (mockDataObj.boutiqueDefaultCarBrandId as number); // state.user references removed – store no longer holds user state
if (mockDataObj.defaultCarId != null) {
state.user.defaultCarId = (mockDataObj.defaultCarId as number);
}
} }
}); });
get_Vehicle_Sales_Data(); get_Vehicle_Sales_Data();
......
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { state } from "@/store/index.uts";
import { computed } from "vue"; import { computed } from "vue";
import { useOrientation } from "@/services/adapter/hooks/useOrientation.uts"; import { useOrientation } from "@/services/adapter/hooks/useOrientation.uts";
...@@ -91,7 +90,7 @@ function getPreferredObjectImage(obj: UTSJSONObject): string { ...@@ -91,7 +90,7 @@ function getPreferredObjectImage(obj: UTSJSONObject): string {
} }
function getImageFromArray(list: Array<any>): string { function getImageFromArray(list: Array<any>): string {
const customerInfo = state.user.customerInfo as UTSJSONObject; const customerInfo = {} as UTSJSONObject;
const carModelId = customerInfo != null ? customerInfo["carModelId"] : null; const carModelId = customerInfo != null ? customerInfo["carModelId"] : null;
if (carModelId != null) { if (carModelId != null) {
for (const item of list) { for (const item of list) {
...@@ -134,7 +133,7 @@ function getPreferredObjectImage(obj: UTSJSONObject): string { ...@@ -134,7 +133,7 @@ function getPreferredObjectImage(obj: UTSJSONObject): string {
return directUrl; return directUrl;
} }
const customerInfo = state.user.customerInfo as UTSJSONObject; const customerInfo = {} as UTSJSONObject;
if (customerInfo != null) { if (customerInfo != null) {
const carModelId = customerInfo["carModelId"]; const carModelId = customerInfo["carModelId"];
if (carModelId != null) { if (carModelId != null) {
......
...@@ -106,7 +106,6 @@ import { ...@@ -106,7 +106,6 @@ import {
import FinishStep from "@/components/FinishStep.uvue"; import FinishStep from "@/components/FinishStep.uvue";
import ToolBox from "@/components/ToolBox.uvue"; import ToolBox from "@/components/ToolBox.uvue";
import { recordService } from "@/services/recorder/index.uts"; import { recordService } from "@/services/recorder/index.uts";
import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts"; import { storage } from "@/utils/storage.uts";
import { callComponentMethod } from "@/utils/common.uts"; import { callComponentMethod } from "@/utils/common.uts";
import type { ToolItem } from "@/types/tool-item.uts"; import type { ToolItem } from "@/types/tool-item.uts";
...@@ -182,18 +181,11 @@ const sceneType = computed<any>(() => { ...@@ -182,18 +181,11 @@ const sceneType = computed<any>(() => {
}); });
const currentCarInfo = computed(() => { const currentCarInfo = computed(() => {
const data = state.user.currentCarInfo; const data = {} as UTSJSONObject;
return data as UTSJSONObject; return data as UTSJSONObject;
}); });
const watchStatus = computed(() => { const watchStatus = computed(() => {
const status = state.user?.historyStatus;
if (status == null) {
return false; return false;
} else if (status == 1) {
return true;
} else {
return false;
}
}); });
const isPreview = computed<boolean>(() => { const isPreview = computed<boolean>(() => {
...@@ -543,7 +535,7 @@ function setViewInfo(data: any): void { ...@@ -543,7 +535,7 @@ function setViewInfo(data: any): void {
currentMediaId.value = ((dataObj?.id ?? "") as string); currentMediaId.value = ((dataObj?.id ?? "") as string);
} }
const viewKey = computed(() => { const viewKey = computed(() => {
return state.user.viewKey; return Date.now();
}); });
async function setPageData() { async function setPageData() {
const carBrandId= currentCarInfo.value.carBrandId; const carBrandId= currentCarInfo.value.carBrandId;
...@@ -679,9 +671,6 @@ function restoreFromStorage(): void { ...@@ -679,9 +671,6 @@ function restoreFromStorage(): void {
} }
onLoad((options) => { onLoad((options) => {
// 初始化客户信息
dispatch("setCustomerInfo", {});
if (options == null) { if (options == null) {
return; return;
} }
...@@ -777,9 +766,6 @@ function choose(e: ToolItem): void { ...@@ -777,9 +766,6 @@ function choose(e: ToolItem): void {
} }
function clearHistory():void{ function clearHistory():void{
dispatch("clearCustomerInfo");
dispatch("clearHistory");
dispatch("clearReceptionTrack");
} }
function backHome():void{ function backHome():void{
uni.navigateBack(); uni.navigateBack();
...@@ -824,7 +810,7 @@ function done(val: string) { ...@@ -824,7 +810,7 @@ function done(val: string) {
// ✅ 使用 callComponentMethod 调用组件方法 // ✅ 使用 callComponentMethod 调用组件方法
callComponentMethod(toolRef, 'hide'); callComponentMethod(toolRef, 'hide');
callComponentMethod(stepRef, 'close'); callComponentMethod(stepRef, 'close');
const customerInfo = state.user.customerInfo as UTSJSONObject; const customerInfo = {} as UTSJSONObject;
recordService.stopAudio(); recordService.stopAudio();
uni.navigateBack(); uni.navigateBack();
// receptionTrackLeave() // receptionTrackLeave()
......
...@@ -23,15 +23,14 @@ import { storage } from "@/utils/storage.uts"; ...@@ -23,15 +23,14 @@ import { storage } from "@/utils/storage.uts";
provideSceneContext("boutique"); provideSceneContext("boutique");
onShow(async () => { onShow(async () => {
const userInfo = storage.get("userInfo"); const userInfoObj = storage.getUserInfo();
if (userInfo == null) { if (userInfoObj == null || JSON.stringify(userInfoObj) === "{}") {
storage.remove("userInfo"); storage.remove("userInfo");
storage.remove("sessionId"); storage.remove("sessionId");
uni.reLaunch({ url: "/pages/common/login/index" }); uni.reLaunch({ url: "/pages/common/login/index" });
return; return;
} }
const userInfoObj = userInfo as UTSJSONObject; const shopMerchantId = (userInfoObj["shopMerchantId"] as string) ?? "";
const shopMerchantId = (userInfoObj.shopMerchantId as string) ?? "";
if (shopMerchantId == null || shopMerchantId === "") { if (shopMerchantId == null || shopMerchantId === "") {
storage.remove("userInfo"); storage.remove("userInfo");
storage.remove("sessionId"); storage.remove("sessionId");
......
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
<view class="reception-session-action-box"> <view class="reception-session-action-box">
<view class="reception-end-btn" <view class="reception-end-btn"
hover-class="reception-end-btn-hover" hover-class="reception-end-btn-hover"
@click="handleBack"> @click="handleFinishReception">
<text class="reception-end-btn-text">结束接待</text> <text class="reception-end-btn-text">结束接待</text>
</view> </view>
</view> </view>
...@@ -68,7 +68,7 @@ ...@@ -68,7 +68,7 @@
<view class="reception-field reception-field-major"> <view class="reception-field reception-field-major">
<view class="reception-field-inner"> <view class="reception-field-inner">
<text class="reception-field-label">手机号</text> <text class="reception-field-label">手机号</text>
<un-input v-model="formData.phoneNumber" <un-input v-model="formData.customerMobile"
class="reception-field-input" class="reception-field-input"
border="none" border="none"
clearable clearable
...@@ -91,7 +91,7 @@ ...@@ -91,7 +91,7 @@
<view class="reception-field reception-field-minor"> <view class="reception-field reception-field-minor">
<view class="reception-field-inner"> <view class="reception-field-inner">
<text class="reception-field-label">品牌</text> <text class="reception-field-label">品牌</text>
<un-input v-model="formData.carBrand" <un-input v-model="formData.brandName"
class="reception-field-input" class="reception-field-input"
border="none" border="none"
clearable clearable
...@@ -102,7 +102,7 @@ ...@@ -102,7 +102,7 @@
<view class="reception-field reception-field-minor"> <view class="reception-field reception-field-minor">
<view class="reception-field-inner"> <view class="reception-field-inner">
<text class="reception-field-label">车系</text> <text class="reception-field-label">车系</text>
<un-input v-model="formData.carSeries" <un-input v-model="formData.seriesName"
class="reception-field-input" class="reception-field-input"
border="none" border="none"
clearable clearable
...@@ -161,10 +161,11 @@ import { computed, ref, watch, onUnmounted, type Ref } from "vue"; ...@@ -161,10 +161,11 @@ import { computed, ref, watch, onUnmounted, type Ref } from "vue";
import ProductIntroGrid from "@/components/ProductIntroGrid.uvue"; import ProductIntroGrid from "@/components/ProductIntroGrid.uvue";
import { useOrientation } from "@/services/adapter/hooks/index.uts"; import { useOrientation } from "@/services/adapter/hooks/index.uts";
import { recordService } from "@/services/recorder/index.uts"; import { recordService } from "@/services/recorder/index.uts";
import { dispatch } from "@/store/index.uts"; import { useReceptionStore, type CustomerInfo } from "@/store/modules/reception.uts";
import { type RecordData } from "@/services/recorder/types";
import receptionPageVars from "./styles/reception.vars.uts"; import receptionPageVars from "./styles/reception.vars.uts";
import { import {
buildCustomerInfoPayload,
createEmptyReceptionForm, createEmptyReceptionForm,
loadReceptionMaterials, loadReceptionMaterials,
readMaterialCoverUrl, readMaterialCoverUrl,
...@@ -175,6 +176,7 @@ import { ...@@ -175,6 +176,7 @@ import {
const pageVarsObject = receptionPageVars as UTSJSONObject; const pageVarsObject = receptionPageVars as UTSJSONObject;
const orientationHook = useOrientation(); const orientationHook = useOrientation();
const receptionStore = useReceptionStore();
const isPortrait = computed((): boolean => { const isPortrait = computed((): boolean => {
const portraitRef = orientationHook.isPortrait as Ref<boolean>; const portraitRef = orientationHook.isPortrait as Ref<boolean>;
...@@ -238,37 +240,73 @@ const materialEmptyText = computed((): string => { ...@@ -238,37 +240,73 @@ const materialEmptyText = computed((): string => {
}); });
watch(formData, () => { watch(formData, () => {
dispatch("setCustomerInfo", buildCustomerInfoPayload(formData.value)); const form = formData.value;
console.log("formData changed", form);
// 1. 更新 reception store
const info: CustomerInfo = {
customerName: form.customerName,
customerMobile: form.customerMobile,
plateNumber: form.plateNumber,
brandId: "",
brandName: form.brandName,
seriesId: "",
seriesName: form.seriesName,
customerId: ""
} as CustomerInfo;
receptionStore.setCustomerInfo(info);
// 2. 同步客户信息到录音服务
const recordData: RecordData = {
customerName: form.customerName,
customerMobile: form.customerMobile,
plateNumber: form.plateNumber,
brandName: form.brandName,
seriesName: form.seriesName
} as RecordData;
recordService.updateBusinessData(recordData);
}, { deep: true, immediate: true }); }, { deep: true, immediate: true });
function resetReceptionDraft(): void { function resetReceptionDraft(): void {
formData.value = createEmptyReceptionForm(); formData.value = createEmptyReceptionForm();
dispatch("setCustomerInfo", buildCustomerInfoPayload(formData.value));
} }
function isWebUrl(url: string): boolean { function isWebUrl(url: string): boolean {
return url.startsWith("http://") || url.startsWith("https://"); return url.startsWith("http://") || url.startsWith("https://");
} }
function closeReception(): void { function closeReception(isNotSave: boolean): void {
if (hasClosed) { if (hasClosed) {
return; return;
} }
hasClosed = true; hasClosed = true;
recordService.stopAudio(true); recordService.stopAudio(isNotSave);
uni.navigateBack(); uni.navigateBack();
} }
function handleBack(): void { function handleFinishReception(): void {
uni.showModal({ uni.showModal({
title: "结束接待", title: "结束接待",
content: "退出后将停止本次接待录音,已录入的客户资料会保留在当前会话中。", content: "确认结束本次接待?录音及客户资料将保存。",
cancelText: "继续接待", cancelText: "继续接待",
confirmText: "结束接待", confirmText: "结束接待",
confirmColor: "#2c66f7", confirmColor: "#2c66f7",
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
closeReception(); closeReception(false);
}
}
});
}
function handleBack(): void {
uni.showModal({
title: "退出接待",
content: "退出后将停止本次接待录音,接待记录不会保存。",
cancelText: "继续接待",
confirmText: "退出",
confirmColor: "#ff4d4f",
success: (res) => {
if (res.confirm) {
closeReception(true);
} }
} }
}); });
......
...@@ -3,10 +3,10 @@ import { getContents } from "@/api/modules/contents.uts"; ...@@ -3,10 +3,10 @@ import { getContents } from "@/api/modules/contents.uts";
export type CustomerReceptionForm = { export type CustomerReceptionForm = {
customerName: string customerName: string
phoneNumber: string customerMobile: string
plateNumber: string plateNumber: string
carBrand: string brandName: string
carSeries: string seriesName: string
} }
const _emptyArr: any[] = [] as any[]; const _emptyArr: any[] = [] as any[];
...@@ -14,10 +14,10 @@ const _emptyArr: any[] = [] as any[]; ...@@ -14,10 +14,10 @@ const _emptyArr: any[] = [] as any[];
export function createEmptyReceptionForm(): CustomerReceptionForm { export function createEmptyReceptionForm(): CustomerReceptionForm {
return { return {
customerName: "", customerName: "",
phoneNumber: "", customerMobile: "",
plateNumber: "", plateNumber: "",
carBrand: "", brandName: "",
carSeries: "" seriesName: ""
}; };
} }
...@@ -146,10 +146,10 @@ export function readMaterialPreviewUrl(item: any | null): string { ...@@ -146,10 +146,10 @@ export function readMaterialPreviewUrl(item: any | null): string {
export function buildCustomerInfoPayload(form: CustomerReceptionForm): UTSJSONObject { export function buildCustomerInfoPayload(form: CustomerReceptionForm): UTSJSONObject {
return { return {
customerName: form.customerName, customerName: form.customerName,
phoneNumber: form.phoneNumber, customerMobile: form.customerMobile,
carPlateNumber: form.plateNumber, carPlateNumber: form.plateNumber,
carBrand: form.carBrand, carBrand: form.brandName,
carModel: form.carSeries carModel: form.seriesName
} as UTSJSONObject; } as UTSJSONObject;
} }
......
...@@ -114,11 +114,10 @@ function flattenRecordUrlListToPaths(urlList: RecordData["urlList"]): string[] { ...@@ -114,11 +114,10 @@ function flattenRecordUrlListToPaths(urlList: RecordData["urlList"]): string[] {
function toReceptionListRowFromLocalRecord(rec: RecordData): UTSJSONObject { function toReceptionListRowFromLocalRecord(rec: RecordData): UTSJSONObject {
return { return {
batchId: rec.id, batchId: rec.id,
machineCode: rec.machineCode ?? "",
recordStatus: rec.recordStatus ?? 0, recordStatus: rec.recordStatus ?? 0,
customerName: rec.customerName ?? "", customerName: rec.customerName ?? "",
carType: rec.carType ?? "", seriesName: rec.seriesName ?? "",
phoneNumber: rec.customerPhone ?? "", phoneNumber: rec.customerMobile ?? "",
result: rec.result ?? "", result: rec.result ?? "",
receptionStartTime: rec.startTime ?? "", receptionStartTime: rec.startTime ?? "",
receptionEndTime: rec.endTime ?? "", receptionEndTime: rec.endTime ?? "",
......
...@@ -523,21 +523,25 @@ const displayCustomerName = computed((): string => { ...@@ -523,21 +523,25 @@ const displayCustomerName = computed((): string => {
const displayCustomerPhone = computed((): string => { const displayCustomerPhone = computed((): string => {
const d = resolvedDetail.value const d = resolvedDetail.value
if (d == null) { return '-' } if (d == null) { return '-' }
// 新结构:customerPhone;旧结构兼容:ownerPhone / phone // 优先 customerMobile,兼容旧字段 customerPhone / ownerPhone / phone
const raw = fieldStr(d, 'customerPhone') const raw = fieldStr(d, 'customerMobile')
if (raw != '') { return formatPhone(raw) } if (raw != '') { return formatPhone(raw) }
const raw2 = fieldStr(d, 'ownerPhone') const raw2 = fieldStr(d, 'customerPhone')
if (raw2 != '') { return formatPhone(raw2) } if (raw2 != '') { return formatPhone(raw2) }
const raw3 = fieldStr(d, 'phone') const raw3 = fieldStr(d, 'ownerPhone')
return orPlaceholder(formatPhone(raw3)) if (raw3 != '') { return formatPhone(raw3) }
const raw4 = fieldStr(d, 'phone')
return orPlaceholder(formatPhone(raw4))
}) })
const displayCarType = computed((): string => { const displayCarType = computed((): string => {
const d = resolvedDetail.value const d = resolvedDetail.value
if (d == null) { return '-' } if (d == null) { return '-' }
// 新结构:carType;旧结构兼容:brandModel // 优先 seriesName,兼容旧字段 carType / brandModel
const v = fieldStr(d, 'carType') const v = fieldStr(d, 'seriesName')
if (v != '') { return v } if (v != '') { return v }
const v2 = fieldStr(d, 'carType')
if (v2 != '') { return v2 }
return orPlaceholder(fieldStr(d, 'brandModel')) return orPlaceholder(fieldStr(d, 'brandModel'))
}) })
...@@ -708,8 +712,8 @@ function parseGoodsListFromDetail(d: UTSJSONObject | null): GoodsCardItem[] { ...@@ -708,8 +712,8 @@ function parseGoodsListFromDetail(d: UTSJSONObject | null): GoodsCardItem[] {
const ownerInfoRows = computed((): FormRowItem[] => { const ownerInfoRows = computed((): FormRowItem[] => {
return [ return [
{ key: 'customerName', label: '客户姓名', value: displayCustomerName.value }, { key: 'customerName', label: '客户姓名', value: displayCustomerName.value },
{ key: 'customerPhone', label: '客户电话', value: displayCustomerPhone.value }, { key: 'customerMobile', label: '客户电话', value: displayCustomerPhone.value },
{ key: 'carType', label: '车型', value: displayCarType.value }, { key: 'seriesName', label: '车型', value: displayCarType.value },
{ key: 'customerType', label: '客户类型', value: displayCustomerType.value }, { key: 'customerType', label: '客户类型', value: displayCustomerType.value },
{ key: 'result', label: '接待结果', value: displayResult.value }, { key: 'result', label: '接待结果', value: displayResult.value },
{ key: 'storeName', label: '门店', value: displayStoreName.value }, { key: 'storeName', label: '门店', value: displayStoreName.value },
......
...@@ -22,12 +22,12 @@ ...@@ -22,12 +22,12 @@
></un-input> ></un-input>
</un-form-item> </un-form-item>
<un-form-item prop="customerPhone" :customStyle="formItemCustomStyle"> <un-form-item prop="customerMobile" :customStyle="formItemCustomStyle">
<template #label> <template #label>
<text class="form-label">车主电话</text> <text class="form-label">车主电话</text>
</template> </template>
<un-input <un-input
v-model="formData.customerPhone" v-model="formData.customerMobile"
border="none" border="none"
type="tel" type="tel"
inputAlign="right" inputAlign="right"
...@@ -51,12 +51,12 @@ ...@@ -51,12 +51,12 @@
</view> </view>
</un-form-item> </un-form-item>
<un-form-item prop="carType" :customStyle="formItemCustomStyle"> <un-form-item prop="seriesName" :customStyle="formItemCustomStyle">
<template #label> <template #label>
<text class="form-label">品牌车型</text> <text class="form-label">品牌车型</text>
</template> </template>
<un-input <un-input
v-model="formData.carType" v-model="formData.seriesName"
border="none" border="none"
inputAlign="right" inputAlign="right"
placeholder="请输入品牌车型" placeholder="请输入品牌车型"
...@@ -109,17 +109,17 @@ import { getCustomerPhone } from '../lists/reception-list-helpers.uts' ...@@ -109,17 +109,17 @@ import { getCustomerPhone } from '../lists/reception-list-helpers.uts'
/** /**
* 编辑页路由 record 与本地库 RecordData / 列表项对齐,常见字段示例: * 编辑页路由 record 与本地库 RecordData / 列表项对齐,常见字段示例:
* id, machineCode, startTime, endTime, recordStatus, endReasonType, * id, storeId, startTime, endTime, recordStatus, endReasonType,
* customerName, customerPhone, customerType, carType, result, * customerName, customerMobile, customerType, seriesName, result,
* urlList[{ filePath, status, file?, filePathOnClient? }], 以及可选 merchantId、userId 等。 * urlList[{ filePath, status, file?, filePathOnClient? }], 以及可选 merchantId、userId 等。
* 表单仅维护客户与结果字段;提交时 deepClone 快照并覆盖表单列,其余字段原样保留。 * 表单仅维护客户与结果字段;提交时 deepClone 快照并覆盖表单列,其余字段原样保留。
*/ */
type EditFormModel = { type EditFormModel = {
id: string id: string
customerName: string customerName: string
customerPhone: string customerMobile: string
customerType: string customerType: string
carType: string seriesName: string
result: string result: string
} }
...@@ -170,9 +170,9 @@ function getEmptyForm(): EditFormModel { ...@@ -170,9 +170,9 @@ function getEmptyForm(): EditFormModel {
return { return {
id: '', id: '',
customerName: '', customerName: '',
customerPhone: '', customerMobile: '',
customerType: '', customerType: '',
carType: '', seriesName: '',
result: '', result: '',
} }
} }
...@@ -305,11 +305,11 @@ function normalizeSaveRecCustomerShape(out: UTSJSONObject, snap: UTSJSONObject): ...@@ -305,11 +305,11 @@ function normalizeSaveRecCustomerShape(out: UTSJSONObject, snap: UTSJSONObject):
} }
} }
const phone = fieldStr(out, 'customerPhone') const phone = fieldStr(out, 'customerMobile')
if (phone == '') { if (phone == '') {
const pn = fieldStr(out, 'phoneNumber') const pn = fieldStr(out, 'phoneNumber')
if (pn != '') { if (pn != '') {
out['customerPhone'] = pn out['customerMobile'] = pn
} }
} }
...@@ -334,9 +334,9 @@ function buildMergedSubmitPayload(snap: UTSJSONObject, fd: EditFormModel): UTSJS ...@@ -334,9 +334,9 @@ function buildMergedSubmitPayload(snap: UTSJSONObject, fd: EditFormModel): UTSJS
return {} as UTSJSONObject return {} as UTSJSONObject
} }
out['customerName'] = fd.customerName out['customerName'] = fd.customerName
out['customerPhone'] = fd.customerPhone out['customerMobile'] = fd.customerMobile
out['customerType'] = fd.customerType out['customerType'] = fd.customerType
out['carType'] = fd.carType out['seriesName'] = fd.seriesName
out['result'] = fd.result out['result'] = fd.result
mergeLoginContextIfEmpty(out) mergeLoginContextIfEmpty(out)
normalizeSaveRecCustomerShape(out, snap) normalizeSaveRecCustomerShape(out, snap)
...@@ -350,9 +350,10 @@ function applyInitialRecord(r: UTSJSONObject): void { ...@@ -350,9 +350,10 @@ function applyInitialRecord(r: UTSJSONObject): void {
next.id = fieldStr(r, 'batchId') next.id = fieldStr(r, 'batchId')
} }
next.customerName = fieldStr(r, 'customerName') next.customerName = fieldStr(r, 'customerName')
next.customerPhone = getCustomerPhone(r) next.customerMobile = getCustomerPhone(r)
next.customerType = fieldStr(r, 'customerType') next.customerType = fieldStr(r, 'customerType')
next.carType = fieldStr(r, 'carType') next.seriesName = fieldStr(r, 'seriesName')
if (next.seriesName == '') { next.seriesName = fieldStr(r, 'carType') }
next.result = fieldStr(r, 'result') next.result = fieldStr(r, 'result')
formData.value = next formData.value = next
} }
...@@ -391,10 +392,10 @@ async function loadFullRecordFromDb(recordId: string, fallbackObj: UTSJSONObject ...@@ -391,10 +392,10 @@ async function loadFullRecordFromDb(recordId: string, fallbackObj: UTSJSONObject
function validateForm(): string | null { function validateForm(): string | null {
const fd = formData.value const fd = formData.value
if (fd.customerName == '') return '请输入车主姓名' if (fd.customerName == '') return '请输入车主姓名'
if (fd.customerPhone == '') return '请输入车主电话' if (fd.customerMobile == '') return '请输入车主电话'
if (!phoneRex.test(fd.customerPhone)) return '请输入正确的手机号码' if (!phoneRex.test(fd.customerMobile)) return '请输入正确的手机号码'
if (fd.customerType == '') return '请选择客户类型' if (fd.customerType == '') return '请选择客户类型'
if (fd.carType == '') return '请输入品牌车型' if (fd.seriesName == '') return '请输入品牌车型'
if (fd.result == '') return '请选择接待结果' if (fd.result == '') return '请选择接待结果'
return null return null
} }
......
...@@ -82,6 +82,8 @@ function getCustomerName(item: UTSJSONObject): string { ...@@ -82,6 +82,8 @@ function getCustomerName(item: UTSJSONObject): string {
} }
function getCarType(item: UTSJSONObject): string { function getCarType(item: UTSJSONObject): string {
const s = getStr(item, 'seriesName')
if (s != '') { return textOrDash(s) }
return textOrDash(getStr(item, 'carType')) return textOrDash(getStr(item, 'carType'))
} }
......
...@@ -70,9 +70,13 @@ export function getArrivalTsForEntry(item: UTSJSONObject): number | null { ...@@ -70,9 +70,13 @@ export function getArrivalTsForEntry(item: UTSJSONObject): number | null {
} }
/** /**
* 获取客户电话(兼容 customerPhone 和 phoneNumber 字段) * 获取客户电话(优先 customerMobile,兼容旧字段 customerPhone 和 phoneNumber)
*/ */
export function getCustomerPhone(item: UTSJSONObject): string { export function getCustomerPhone(item: UTSJSONObject): string {
const m = getStr(item, 'customerMobile')
if (!isBlankDisplayText(m)) {
return m
}
const p = getStr(item, 'customerPhone') const p = getStr(item, 'customerPhone')
if (!isBlankDisplayText(p)) { if (!isBlankDisplayText(p)) {
return p return p
......
...@@ -380,7 +380,8 @@ const cardCustomerName = computed((): string => getItemStr("customerName")); ...@@ -380,7 +380,8 @@ const cardCustomerName = computed((): string => getItemStr("customerName"));
/** 脱敏:第 4~7 位替换为 ****(与功能清单 slice(3,7) 一致) */ /** 脱敏:第 4~7 位替换为 ****(与功能清单 slice(3,7) 一致) */
const cardPhoneDesensitized = computed((): string => { const cardPhoneDesensitized = computed((): string => {
const raw = getItemStr("customerPhone").replace(/\s/g, ""); let raw = getItemStr("customerMobile").replace(/\s/g, "");
if (raw == "") { raw = getItemStr("customerPhone").replace(/\s/g, ""); }
if (raw.length < 7) { if (raw.length < 7) {
return raw; return raw;
} }
...@@ -397,6 +398,10 @@ const cardTagBrand = computed((): string => { ...@@ -397,6 +398,10 @@ const cardTagBrand = computed((): string => {
}); });
const cardTagModel = computed((): string => { const cardTagModel = computed((): string => {
const seriesName = getItemStr("seriesName");
if (seriesName != "") {
return seriesName;
}
const carType = getItemStr("carType"); const carType = getItemStr("carType");
if (carType != "") { if (carType != "") {
return carType; return carType;
......
...@@ -21,12 +21,16 @@ const BASE_COLUMNS = [ ...@@ -21,12 +21,16 @@ const BASE_COLUMNS = [
// `receptionEndTime TEXT`, // `receptionEndTime TEXT`,
// `receptionStatus INTEGER`, // `receptionStatus INTEGER`,
// `recordUrlList TEXT`, // `recordUrlList TEXT`,
`endReasonType INTEGER`, `storeId TEXT`,
`customerId TEXT`,
`customerName TEXT`,
`customerMobile TEXT`,
`endReasonType TEXT`,
`startTime TEXT`, `startTime TEXT`,
`endTime TEXT`, `endTime TEXT`,
`result TEXT`, `result TEXT`,
`urlList TEXT`, `urlList TEXT`,
`recordStatus INTEGER DEFAULT 0` `recordStatus TEXT DEFAULT '0'`
]; ];
const defaultStrategy = RecorderStrategyFactory.getDefaultStrategy(); const defaultStrategy = RecorderStrategyFactory.getDefaultStrategy();
......
...@@ -21,8 +21,8 @@ import { FileStatus } from "./common/constants.uts"; ...@@ -21,8 +21,8 @@ import { FileStatus } from "./common/constants.uts";
import { toStr, toObj, toNum, toStrArr, toObjArr, toBool, deepClone, type StrOrNull } from "@/utils/common.uts"; import { toStr, toObj, toNum, toStrArr, toObjArr, toBool, deepClone, type StrOrNull } from "@/utils/common.uts";
import DBRecord from "./DBRecord.uts"; import DBRecord from "./DBRecord.uts";
import { FileBeforeUpload ,RecordFile } from "./types/audio.uts"; import { FileBeforeUpload ,RecordFile } from "./types/audio.uts";
// ✅ 导入 sys store state 获取应用后台状态 // ✅ 导入 sys store 获取应用后台状态
import { state as sysState } from "@/store/modules/sys.uts"; import { useSysStore } from "@/store/modules/sys.uts";
/** /**
* ✅ 序列化对象为字符串(用于日志输出) * ✅ 序列化对象为字符串(用于日志输出)
...@@ -148,7 +148,7 @@ class RecordSave { ...@@ -148,7 +148,7 @@ class RecordSave {
async _checkStopConditions(): Promise<StrOrNull> { async _checkStopConditions(): Promise<StrOrNull> {
// ✅ 检查应用是否在后台运行 // ✅ 检查应用是否在后台运行
const isBackground = sysState.isInBackground; const isBackground = useSysStore().state.isInBackground;
if (isBackground) { if (isBackground) {
return "APP在后台运行,不进行文件上传"; return "APP在后台运行,不进行文件上传";
} }
......
...@@ -82,10 +82,7 @@ export class RecordService { ...@@ -82,10 +82,7 @@ export class RecordService {
return this.record; return this.record;
} }
initRecord() { initRecord() {
const { deviceId } = uni.getDeviceInfo(); this.initialRecord = {} as UTSJSONObject;
this.initialRecord = {
machineCode:deviceId
};
} }
/** /**
......
...@@ -78,38 +78,11 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -78,38 +78,11 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
*/ */
getTableColumns(): string[] { getTableColumns(): string[] {
return [ return [
// `staffUuid TEXT`, 'plateNumber TEXT',
// `staffName TEXT`, 'brandId TEXT',
// `serviceMerchantId TEXT`, 'brandName TEXT',
// `carModel TEXT`, 'seriesId TEXT',
// `carModelId TEXT`, 'seriesName TEXT'
// `customerName TEXT`,
// `customerType TEXT`,
// `phoneNumber TEXT`,
// `appCode TEXT`,
// `loginPhone TEXT`,
// `salesName TEXT`,
// `salesUuid TEXT`,
// `receptionCustomerPaySourceList TEXT DEFAULT '[]'`,
// `merchantId TEXT`,
// `merchantName TEXT`,
// `bussinessType TEXT`,
// `channelType TEXT`,
// `receptionCustomerMaterialPointList TEXT DEFAULT '[]'`,
// `carBrand TEXT`,
// `carBrandId TEXT`,
// `oneCarBrand TEXT`,
// `oneCarBrandId TEXT`,
'typeCode TEXT',
'carType TEXT',
'merchantId TEXT',
'machineCode TEXT',
'customerType TEXT',
'customerName TEXT',
'customerPhone TEXT',
`userId TEXT`,
`userName TEXT`,
'materialId TEXT'
]; ];
} }
...@@ -166,31 +139,16 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -166,31 +139,16 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
/** /**
* 获取动态业务属性 * 获取动态业务属性
*/ */
private getDynamicAttributes(): RecordData { private getDynamicAttributes(): UTSJSONObject {
// const info = uni.getDeviceInfo();
const obj = storage.getParse("userInfo"); const obj = storage.getParse("userInfo");
// console.log("🚀 ~ DefaultRecorderStrategy ~ getDynamicAttributes ~ obj:", obj)
const typeItem = storage.getParse('typeItem');
// console.log("🚀 ~ DefaultRecorderStrategy ~ getDynamicAttributes ~ typeItem:", typeItem)
const materialId = "101" //TODO //storage.getParse("materialId");
// console.log("🚀 ~ DefaultRecorderStrategy ~ getDynamicAttributes ~ materialId:", materialId)
// const user = obj.get("user");
const userId = getStringProp(obj, "userId"); const userId = getStringProp(obj, "userId");
const userName = getStringProp(obj, "userName"); const userName = getStringProp(obj, "userName");
const merchantId = getStringProp(obj, "shopMerchantId"); const storeId = getStringProp(obj, "storeId");
const typeCode = getStringProp(typeItem, "typeCode");
// const machineCode = info.deviceId;
return { return {
userId, userId: userId,
userName, userName: userName,
merchantId, storeId: storeId,
typeCode, } as UTSJSONObject;
materialId,
// machineCode,
};
} }
/** /**
...@@ -199,22 +157,20 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -199,22 +157,20 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
* @param extendedRecord 扩展记录对象(包含缓存和动态属性) * @param extendedRecord 扩展记录对象(包含缓存和动态属性)
* @returns 深拷贝后的合并结果 * @returns 深拷贝后的合并结果
*/ */
private mergeData(baseRecord: RecordData, extendedRecord: RecordData): RecordData { private mergeData(baseRecord: any, extendedRecord: any): RecordData {
const merged: RecordData = {} as RecordData; const merged: RecordData = {} as RecordData;
// 先合并基础记录 // 先合并基础记录
if (baseRecord !== null) { if (baseRecord != null) {
const baseObj = deepClone<RecordData>(baseRecord); const baseMap = toMap(baseRecord);
const baseMap = toMap(baseObj);
baseMap.forEach((value, key) => { baseMap.forEach((value, key) => {
merged[key] = value ?? null; merged[key] = value ?? null;
}); });
} }
// 再合并扩展记录(覆盖基础记录的字段) // 再合并扩展记录(覆盖基础记录的字段)
if (extendedRecord !== null) { if (extendedRecord != null) {
const extendedObj = deepClone<RecordData>(extendedRecord); const extendedMap = toMap(extendedRecord);
const extendedMap = toMap(extendedObj);
extendedMap.forEach((value, key) => { extendedMap.forEach((value, key) => {
merged[key] = value ?? null; merged[key] = value ?? null;
}); });
......
...@@ -7,26 +7,28 @@ export type IRecordDataBase = { ...@@ -7,26 +7,28 @@ export type IRecordDataBase = {
result?: null | string result?: null | string
recordStatus?: null | number recordStatus?: null | number
urlList?: null | RecordFile[], urlList?: null | RecordFile[],
storeId?: null | string,
customerId?: null | string,
customerName?: null | string,
customerMobile?: null | string,
endReasonType?: null | number
} }
export type RecordData = { export type RecordData = {
id?: string id?: string
machineCode?: null | string
startTime?: null | string startTime?: null | string
endTime?: null | string
urlList?: null | RecordFile[]|string[] urlList?: null | RecordFile[]|string[]
customerId?: null | string
customerName?: null | string customerName?: null | string
customerPhone?: null | string customerMobile?: null | string
customerType?: null | string customerType?: null | string
carType?: null | string plateNumber?: null | string
endTime?: null | string
result?: null | string result?: null | string
userId?: null | string brandId?: null | string
userName?: null | string brandName?: null | string
merchantId?: null | string seriesId?: null | string
typeCode?: null | string seriesName?: null | string
// merchantName?: null | string
// phoneNumber?: null | string
materialId?: null | string
endReasonType?: null | number endReasonType?: null | number
recordStatus?: null | number // 0: recording, 1: completed recordStatus?: null | number // 0: recording, 1: completed
} }
...@@ -37,8 +39,8 @@ export type RecordData = { ...@@ -37,8 +39,8 @@ export type RecordData = {
export type CustomerInfoData = { export type CustomerInfoData = {
customerName?: null | string customerName?: null | string
customerType?: null | string customerType?: null | string
carType?: null | string seriesName?: null | string
customerPhone?: null | string customerMobile?: null | string
result?: null | string result?: null | string
} }
......
# 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'])
}
}
```
/** import { createPinia } from '@/uni_modules/x-pinia-s'
* Vuex 风格 Store(uni-app x 专用模块方案)
* 模块化重构版本:手动导入模块,自动注册
*/
import { reactive } from "vue";
import { state as audioState, AudioStateType } from "@/store/modules/audio.uts"; export const pinia = createPinia()
import * as audio from "@/store/modules/audio.uts";
import { state as boutiqueState, BoutiqueStateType } from "@/store/modules/boutique.uts";
import * as boutique from "@/store/modules/boutique.uts";
import { state as pointState, PointStateType } from "@/store/modules/point.uts";
import * as point from "@/store/modules/point.uts";
import { state as sysState, SysStateType } from "@/store/modules/sys.uts";
import * as sys from "@/store/modules/sys.uts";
import { state as updateState, UpdateStateType } from "@/store/modules/update.uts";
import * as update from "@/store/modules/update.uts";
import { state as userState, UserStateType } from "@/store/modules/user.uts";
// 1. 导入所有模块
// UTS 目前不支持 import.meta.glob,需要手动导入
import * as user from "@/store/modules/user.uts";
// 2. 模块列表(新增模块需在此处添加) export { useSysStore } from '@/store/modules/sys.uts'
// 这里使用 any 类型数组来规避类型检查问题,实际运行时会通过 UTSJSONObject 处理 export { useReceptionStore } from '@/store/modules/reception.uts'
const modules: any[] = [user, audio, sys, point, boutique, update];
// 聚合所有模块的 getters
const allGetters = {} as UTSJSONObject;
// 遍历模块进行聚合
for (const module_ of modules) {
const mod = module_ as UTSJSONObject;
// 动态聚合 getters
const modGetters = mod.getters as null | UTSJSONObject;
if (modGetters !== null) {
modGetters.toMap().forEach((getterFn, getterName) => {
allGetters[getterName] = getterFn;
});
}
}
// ============ 聚合 State ============
// 为了保持类型安全和代码提示,State 仍然建议静态定义
export class RootState {
audio: AudioStateType = audioState;
boutique: BoutiqueStateType = boutiqueState;
point: PointStateType = pointState;
sys: SysStateType = sysState;
update: UpdateStateType = updateState;
user: UserStateType = userState;
}
export const state = reactive(new RootState());
// ============ 全局 Getters ============
function _getSiteData(): any {
const site = (state as UTSJSONObject).site;
return (site !== null ? (site as UTSJSONObject).siteData : null) as any;
}
allGetters.siteData = (): any => _getSiteData();
export const getters = allGetters;
// ============ 动态 Dispatch 实现 ============
export function dispatch(actionName: string, payload: any = ({} as any)): any | null {
// 遍历所有已加载的模块查找 action
for (const module_ of modules) {
const mod = module_ as UTSJSONObject;
const actions = mod.actions as null | UTSJSONObject;
if (actions !== null) {
const handler = actions[actionName];
if (typeof handler === "function") {
// 执行找到的第一个匹配 Action
return (handler as (payload: any) => any | null)(payload);
}
}
}
console.warn(`[Store] Action not found: ${actionName}`);
return null;
}
/**
* 录音业务联动:更新视图并写入当前车信息。
* action 名字符串仅在 .uts 字面量中出现,避免 uvue 内 dispatch 首参触发 Android kotlin/java String 桥接报错。
*/
export function dispatchRecordCarSelectLinkage(selectItemVal: any): void {
dispatch("updateViewKey");
dispatch("setCurrentCarInfo", selectItemVal);
}
/** 写入门店车品牌列表到 store(action 名仅在 .uts 字面量) */
export function dispatchSetCarBrandsList(carBrandListData: any): void {
dispatch("setCarBrandsList", carBrandListData);
}
/** commit:兼容 mapMutations,内部转调 dispatch */
export function commit(type: string, payload?: any): void {
// 忽略命名空间前缀,直接查找方法名
const name = type.includes("/") ? type.split("/")[1] : type;
dispatch(name, payload != null ? payload : ({} as any));
}
// ============ Store 对象导出 ============
export const store = {
state,
getters,
dispatch: (actionName: string, payload?: any): any | null => dispatch(actionName, payload != null ? payload : ({} as any)),
commit: (type: string, payload?: any): void => commit(type, payload)
};
export default store;
/**
* Vuex 风格 mapHelpers,兼容旧项目 mapState、mapGetters、mapMutations
* 用法与 vuex 一致,迁移时只需改 import 路径
*
* import { mapState, mapGetters, mapMutations } from '@/store/mapHelpers.uts'
* import store from '@/store/index.uts'
*/
import type { RootState } from "./index.uts";
/** 组件实例类型(含 $store) */
type ComponentThis = {
$store: {
commit: (type: string, payload?: any) => void
dispatch: (name: string, payload?: any) => void
getters: Record<string, any>
state: RootState
}
}
/**
* mapState - 映射 state 到 computed
* mapState(['user']) => { user: () => this.$store.state.user }
* mapState('audio', ['isEnd','isStart']) => { isEnd: () => this.$store.state.audio.isEnd, ... }
* mapState(['point.tabIndex']) => { 'point.tabIndex': () => this.$store.state.point.tabIndex }
*/
export function mapState(map: string[]): Record<string, () => any>
export function mapState(namespace: string, map: string[]): Record<string, () => any>
export function mapState(
namespaceOrMap: string | string[],
map?: string[]
): Record<string, () => any> {
if (typeof namespaceOrMap === "string" && map != null) {
// mapState('audio', ['isEnd','isStart'])
const ns = namespaceOrMap;
const result: Record<string, () => any> = {};
for (const key of map) {
result[key] = function (this: ComponentThis): any {
const moduleState = (this.$store.state as any)[ns];
return moduleState != null ? moduleState[key] : null;
};
}
return result;
}
// mapState(['user','point.tabIndex'])
const keys = namespaceOrMap as string[];
const result: Record<string, () => any> = {};
for (const path of keys) {
const localKey = path.includes(".") ? path : path;
result[localKey] = function (this: ComponentThis): any {
const parts = path.split(".");
let v: any = this.$store.state;
for (const part of parts) {
v = v != null ? v[part] : null;
}
return v;
};
}
return result;
}
/**
* mapGetters - 映射 getters 到 computed
* mapGetters(['customerInfo','receptionStatus'])
*/
export function mapGetters(keys: string[]): Record<string, () => any> {
const result: Record<string, () => any> = {};
for (const key of keys) {
result[key] = function (this: ComponentThis): any {
const g = this.$store.getters as Record<string, any>;
if (g == null || g[key] === undefined) return null;
const v = g[key];
return typeof v === "function" ? v() : v;
};
}
return result;
}
/**
* mapMutations - 映射 mutations 到 methods
* mapMutations('audio', ['setReceptionStatus','setBooks','setPerRecordNumber'])
* mapMutations(['clearCustomerInfo'])
*/
export function mapMutations(map: string[]): Record<string, (payload?: any) => void>
export function mapMutations(
namespace: string,
map: string[]
): Record<string, (payload?: any) => void>
export function mapMutations(
namespaceOrMap: string | string[],
map?: string[]
): Record<string, (payload?: any) => void> {
if (typeof namespaceOrMap === "string" && map != null) {
const ns = namespaceOrMap;
const result: Record<string, (payload?: any) => void> = {};
for (const key of map) {
result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.commit(`${ns}/${key}`, payload);
};
}
return result;
}
const keys = namespaceOrMap as string[];
const result: Record<string, (payload?: any) => void> = {};
for (const key of keys) {
result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.commit(key, payload);
};
}
return result;
}
/**
* mapActions - 映射 actions 到 methods(兼容旧项目若有使用)
* mapActions(['setCustomerInfo','clearHistory'])
*/
export function mapActions(keys: string[]): Record<string, (payload?: any) => void> {
const result: Record<string, (payload?: any) => void> = {};
for (const key of keys) {
result[key] = function (this: ComponentThis, payload?: any): void {
this.$store.dispatch(key, payload);
};
}
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"
import { defineStore, PiniaStoreBase } from '@/uni_modules/x-pinia-s'
export type ReceptionState = {
booksList: UTSJSONObject[] export type CustomerInfo = {
customerInfo: null | UTSJSONObject customerName: string
customerKey: string customerMobile: string
receptionKey: string plateNumber: string
receptionStatus: string brandId: string
receptionTrack: UTSJSONObject[] brandName: string
seriesId: string
seriesName: string
customerId: string
} }
// 模块状态 type ReceptionState = {
export const receptionState = reactive({ customerInfo: CustomerInfo | null
customerKey: "", }
customerInfo: null,
receptionStatus: "",
booksList: [],
receptionKey: "",
receptionTrack: []
} as ReceptionState);
// 模块变更方法 (Mutations)
export const setCustomerKey = (payload: string) => {
receptionState.customerKey = payload;
};
export const setCustomerInfo = (payload: null | UTSJSONObject) => {
receptionState.customerInfo = payload;
};
export const setReceptionStatus = (payload: string) => { export class ReceptionStore extends PiniaStoreBase {
receptionState.receptionStatus = payload; state: ReceptionState = reactive<ReceptionState>({
}; customerInfo: null
})
export const setBookList = (payload: UTSJSONObject[]) => { constructor() {
receptionState.booksList = payload; super()
}; this.bindState(this.state)
}
export const setReceptionKey = (payload: string) => { setCustomerInfo(info: CustomerInfo | null): void {
receptionState.receptionKey = payload; this.state.customerInfo = info
}; }
}
export const setReceptionTrack = (payload: UTSJSONObject[]) => { export const useReceptionStore = defineStore<ReceptionStore>('reception', () : ReceptionStore => new ReceptionStore())
receptionState.receptionTrack = payload;
};
import { reactive } from "vue"; import { reactive } from "vue"
import { logger } from "@/services/logger/index.uts"; import { defineStore, PiniaStoreBase } from '@/uni_modules/x-pinia-s'
export class SysStateType { import { logger } from "@/services/logger/index.uts"
static _C: string = "companion";
activityWindowPopStatus: any = 0; type SysState = {
isInBackground: boolean = false; activityWindowPopStatus: any
isInBackground: boolean
} }
export const state = reactive(new SysStateType()); export class SysStore extends PiniaStoreBase {
state: SysState = reactive<SysState>({
activityWindowPopStatus: 0,
isInBackground: false
})
constructor() {
super()
this.bindState(this.state)
}
export const getters = { setBackgroundState(payload: boolean): void {
isInBackground: (): boolean => (state as SysStateType).isInBackground, this.state.isInBackground = payload != false
activityWindowPopStatus: (): any => (state as SysStateType).activityWindowPopStatus logger.warn(`【===== App 切换到${payload ? "后台" : "前台"} =====】`, "SysState")
}; }
export const actions = { setActivityWindowPopCount(payload: any): void {
setBackgroundState: (payload: boolean): any | null => { this.state.activityWindowPopStatus = payload != null ? payload : 0
(state as SysStateType).isInBackground = payload != false; logger.warn(`setActivityWindowPopCount: ${payload}`, "SysState")
logger.warn(`【===== App 切换到${payload ? "后台" : "前台"} =====】`, "SysState");
return null;
},
setActivityWindowPopCount: (payload: any): any | null => {
(state as SysStateType).activityWindowPopStatus = payload != null ? payload : 0;
logger.warn(`setActivityWindowPopCount: ${payload}`, "SysState");
return null;
} }
}; }
export const useSysStore = defineStore<SysStore>('sys', () : SysStore => new SysStore())
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: "",
customerType: "",
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: number = 0;
boutiqueMediaConfig: Record<string, any> = {} as Record<string, any>;
carBrands: any[] = [];
currentCarInfo: UTSJSONObject = {} as UTSJSONObject;
customerInfo: UTSJSONObject = parseCustomerInfo(storage.get("customerInfo") as any);
customerKey: number = Date.now();
defaultCarId: number = 0;
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 UTSJSONObject;
return null;
},
getCustomerInfo: (payload: any): any | null => {
return (state as UserStateType).customerInfo;
}
};
import { RecordService } from "@/services/recorder/index.uts"; import { RecordService } from "@/services/recorder/index.uts";
import TempRecord from "@/services/recorder/TempRecord.uts"; import TempRecord from "@/services/recorder/TempRecord.uts";
import { RecordData } from "@/services/recorder/types/index.uts"; import { RecordData } from "@/services/recorder/types/index.uts";
import { commit } from "@/store/index.uts";
/** /**
* 测试 RecordService 的监听器功能 * 测试 RecordService 的监听器功能
...@@ -81,26 +80,17 @@ export function testRecordWatchers() { ...@@ -81,26 +80,17 @@ export function testRecordWatchers() {
console.log("[Test] 正在触发 Store 变化..."); console.log("[Test] 正在触发 Store 变化...");
// --- 测试 updateCustomerInfo (debounce 1000ms) --- // --- 测试 updateCustomerInfo (debounce 1000ms) ---
// 监听的是 customerKey 变化,回调中使用 customerInfo // commit 调用已移除(旧 store API 不再可用)
const testCustomerInfo = { customerName: "测试客户", phoneNumber: "13800000000" }; const testCustomerInfo = { customerName: "测试客户", phoneNumber: "13800000000" };
commit("updateCustomerInfo", testCustomerInfo);
// 触发 watcher
commit("updateCustomerKey", `KEY_${ Date.now()}`);
// --- 测试 updateReceptionStatus (debounce 200ms) --- // --- 测试 updateReceptionStatus (debounce 200ms) ---
commit("updateReceptionStatus", "1"); // 状态变更 // commit 调用已移除
// --- 测试 updateBookList (debounce 1500ms) --- // --- 测试 updateBookList (debounce 1500ms) ---
const testBookList = [{ id: "book1", imgUrl: "url1" }]; const testBookList = [{ id: "book1", imgUrl: "url1" }];
commit("updateBookList", testBookList); // 数组变更可能不触发 watcher?
// 注意:监听的是 storeState.booksList 引用变化。commit 会替换数组,应该能触发。
// --- 测试 updateMaterialPointList (debounce 1000ms) --- // --- 测试 updateMaterialPointList (debounce 1000ms) ---
// 监听 receptionKey,回调中使用 receptionTrack
const testTrack = [{ id: "point1", x: 10, y: 20 }]; const testTrack = [{ id: "point1", x: 10, y: 20 }];
commit("updateReceptionTrack", testTrack);
// 触发 watcher
commit("updateReceptionKey", `REC_KEY_${ Date.now()}`);
// 4. 等待 Debounce 结束 // 4. 等待 Debounce 结束
// 最长 delay 是 1500ms,我们等待 2000ms // 最长 delay 是 1500ms,我们等待 2000ms
......
import store from '@/store/index.uts' import { pinia, useSysStore } from '@/store/index.uts'
import { watch } from 'vue' import { watch } from 'vue'
export function testStore() { export function testStore() {
console.log("=== 开始 Store 测试 ===") console.log("=== 开始 Store 测试 ===")
const sysStore = useSysStore()
// 1. 初始状态检查 // 1. 初始状态检查
const initVal = store.state.customerKey console.log(`初始 isInBackground: ${sysStore.state.isInBackground}`)
console.log(`初始 customerKey: '${initVal}'`)
// 2. 设置监听器 (模拟 RecordService) // 2. 设置监听器
const stopWatch = watch( const stopWatch = watch(
() => store.state.customerKey, () => sysStore.state.isInBackground,
(newVal, oldVal) => { (newVal: boolean, oldVal: boolean) => {
console.log(`[Watch] customerKey 发生变化: '${oldVal}' -> '${newVal}'`) console.log(`[Watch] isInBackground 发生变化: ${oldVal} -> ${newVal}`)
}, },
{ immediate: false } { immediate: false }
) )
// 3. 执行 Commit // 3. 执行 Action
console.log("执行 commit('updateCustomerKey', 'TEST_KEY_123')...") console.log("执行 setBackgroundState(true)...")
store.commit('updateCustomerKey', 'TEST_KEY_123') sysStore.setBackgroundState(true)
// 4. 验证状态 // 4. 验证状态
// 验证扁平化访问 const pass = sysStore.state.isInBackground === true
const flatState = store.state.customerKey console.log(`验证状态: ${pass ? 'PASS' : 'FAIL'} (期望: true, 实际: ${sysStore.state.isInBackground})`)
const flatPass = flatState === 'TEST_KEY_123'
console.log(`验证扁平化访问: ${flatPass ? 'PASS' : 'FAIL'} (期望: 'TEST_KEY_123', 实际: '${flatState}')`)
// 验证模块化访问
const moduleState = store.state.reception.customerKey
const modulePass = moduleState === 'TEST_KEY_123'
console.log(`验证模块化访问: ${modulePass ? 'PASS' : 'FAIL'} (期望: 'TEST_KEY_123', 实际: '${moduleState}')`)
// 5. 清理 // 5. 清理
stopWatch() stopWatch()
sysStore.setBackgroundState(false)
// 恢复状态 (可选)
// store.commit('updateCustomerKey', initVal)
console.log("=== Store 测试结束 ===") console.log("=== Store 测试结束 ===")
} }
import { watch } from "vue"; import { pinia } from "@/store/index.uts";
import { useSysStore } from "@/store/index.uts";
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() { export function runStoreTest() {
console.log("=== 开始 Store 测试 (V2) ==="); console.log("=== 开始 Store 测试 (V2) ===");
// 1. 基础对象获取 // 验证 pinia 实例已创建
// store 在 UTS 中作为导入对象,视为 UTSJSONObject console.log(`pinia 实例: ${pinia != null ? "已创建" : "未创建"}`);
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();
// 恢复状态 // 验证 sys store 可用
commitFn("clearCustomerInfo", {}); const sysStore = useSysStore();
dispatchFn("setReceptionStatus", ""); console.log(`sysStore isInBackground: ${sysStore.isInBackground}`);
console.log(`sysStore activityWindowPopStatus: ${sysStore.activityWindowPopStatus}`);
console.log("=== Store 测试结束 ==="); console.log("=== Store 测试结束 ===");
} }
## 1.0.0(2026-04-21)
* 发布Pinia by Uts,用法接近原版,请仔细阅读文档再作迁移方案。
/**
* x-pinia-s
*
* uni-app-x 严格类型版 Pinia,class extends 风格。
*
* @example
* ```uts
* // main.uts
* import { createSSRApp } from 'vue'
* import App from './App.uvue'
* import { createPinia } from '@/uni_modules/x-pinia-s'
*
* export function createApp() {
* const app = createSSRApp(App)
* const pinia = createPinia()
* app.use(pinia)
* return { app }
* }
* ```
*
* @author tmui4x
* @copyright https://tmui.design
*/
// ============ 类型 ============
export {
UnsubscribeFn,
SubscriptionMutationType,
SubscriptionMutation,
StateSubscriptionCallback,
ActionContext,
AfterActionCallback,
OnErrorActionCallback,
ActionSubscriptionCallback,
IPinia,
PiniaPlugin,
PiniaPluginContext,
PersistOptions,
PersistSerializer
} from './instans/types.uts'
// ============ Store 基类 ============
export { PiniaStoreBase } from './instans/storeBase.uts'
// ============ 核心 API ============
export { createPinia } from './instans/createPinia.uts'
export { defineStore } from './instans/defineStore.uts'
export { setActivePinia, getActivePinia } from './instans/rootState.uts'
// ============ 持久化 ============
export { createPersistPlugin, clearPersistedState } from './instans/persist.uts'
// ============ Options API 辅助函数(仅 mapState 系列) ============
export {
mapState,
mapStateMapped
} from './instans/mapHelpers.uts'
/**
* Pinia 根实例
*
* createPinia() 创建一个 Pinia,承担:
* - 维护全部 store 的实例缓存
* - 维护插件列表
* - 暴露 Vue 插件 install(app) 接口(app.use(pinia))
*
* 注意:install() 不会自动赋值 app.config.globalProperties.$pinia
* (因为 globalProperties 要求顶层变量赋值,install 内 this 是局部值)。
* 如需 this.$pinia 模板访问,请在 main.uts 顶层手动赋值。
*/
import { IPinia, PiniaPlugin, PiniaPluginContext } from './types.uts'
import { setActivePinia } from './rootState.uts'
import { PiniaStoreBase } from './storeBase.uts'
class Pinia implements IPinia {
override state : UTSJSONObject = {}
override _stores : Map<string, any> = new Map<string, any>()
override _plugins : Array<PiniaPlugin> = []
/**
* Pinia 顶层 effect 作用域。
* 字段初始化器中调用 `effectScope()` —— 因为 Pinia 必须在 main.uts 顶层 createPinia()
* 创建(见 readme),此时 currentScope 为 null,effectScope() 创建出来的就是顶层独立 scope。
* 每个 store 在 defineStore 中通过 `pinia._e.run(() => effectScope())` 创建子 scope,
* 嵌套在本 scope 下,与组件生命周期完全解耦。
*/
override _e : EffectScope = effectScope()
private _installed : boolean = false
constructor() { }
/**
* Vue app.use(pinia) 时被调用
*/
override install(app : VueApp) : void {
if (this._installed) {
console.warn('[x-pinia-s] pinia already installed on a Vue app')
return
}
this._installed = true
// 设置为活动 pinia(首个 install 的实例自动成为活动实例)
setActivePinia(this as IPinia)
// 注意:这里**不会**自动给 app.config.globalProperties.$pinia 赋值。
// 因为官方规定(见 readme「Options API 接入」章节):app-android 平台
// globalProperties 赋值要求顶层变量,install() 内的 this 是运行时局部值,违反规范。
// 如需 this.$pinia 模板访问,请在 main.uts 顶层手动赋值:
// const pinia = createPinia()
// app.config.globalProperties.$pinia = pinia
}
/**
* 注册插件
*/
override use(plugin : PiniaPlugin) : IPinia {
this._plugins.push(plugin)
// 闭包内捕获 this 在 UTS 严格模式下不可靠,先把 this 引用提到外部
const piniaRef : IPinia = this
// 已经实例化的 store 也应用此插件(与 Pinia 行为一致)
this._stores.forEach((store : any, _id : string) : void => {
applyPluginToStore(piniaRef, store, plugin)
})
return this
}
}
/**
* 把单个插件应用到单个 store 上
* @internal 包内使用
*
* store 参数为 any(实际为 PiniaStoreBase 子类实例),
* 内部 cast 为 PiniaStoreBase 后访问 $id / $state(继承关系,类型安全)。
*/
export function applyPluginToStore(pinia : IPinia, store : any, plugin : PiniaPlugin) : void {
// store 是 PiniaStoreBase 子类实例(CounterStore extends PiniaStoreBase),
// 向上 cast 为 PiniaStoreBase 是类型安全的(继承关系),可以直接访问 $id / $state 属性
const storeBase : PiniaStoreBase = store as any as PiniaStoreBase
const ctx : PiniaPluginContext = {
pinia: pinia,
storeId: storeBase.$id,
store: store,
state: storeBase.$state!
}
try {
plugin(ctx)
} catch (e) {
console.warn('[x-pinia-s] plugin error on store ' + ctx.storeId + ':', e)
}
}
/**
* 创建一个 Pinia 实例
*/
export function createPinia() : IPinia {
const pinia : IPinia = new Pinia()
// 自动设置为活动 pinia,方便单实例场景下 useStore() 直接可用
setActivePinia(pinia)
return pinia
}
/**
* defineStore:定义一个 store
*
* UTS class-based 风格:用户先定义一个继承 PiniaStoreBase 的 class,
* defineStore 接受一个返回该 class 实例的工厂函数。
*
* @example
* ```uts
* import { defineStore, PiniaStoreBase } from '@/uni_modules/x-pinia-s'
*
* type CounterState = { count : number }
*
* export class CounterStore extends PiniaStoreBase {
* state : CounterState = reactive({ count: 0 } as CounterState)
* doubled : ComputedRef<number> = computed(() : number => this.state.count * 2)
* increment : () => void = this.withAction('increment', () : void => {
* this.state.count++
* }) as () => void
*
* constructor() {
* super()
* this.bindState(this.state)
* }
* }
*
* export const useCounterStore = defineStore<CounterStore>('counter', () : CounterStore => new CounterStore())
* ```
*/
import { getActivePinia } from './rootState.uts'
import { applyPluginToStore } from './createPinia.uts'
import { PiniaStoreBase } from './storeBase.uts'
/**
* 定义一个 store。
*
* @param id store 的全局唯一 id
* @param factory 返回 PiniaStoreBase 子类实例的工厂函数
* @returns useStore 函数;同 id 单例
*
* 注:T 不加 `extends PiniaStoreBase` 约束 —— UTS 项目暂未发现泛型约束的稳定使用,
* 改为运行时把实例 cast 为 PiniaStoreBase 完成初始化。
*/
export function defineStore<T>(
id : string,
factory : () => T
) : () => T {
return () : T => {
const pinia = getActivePinia()
if (pinia == null) {
throw new Error('[x-pinia-s] no active Pinia. 请先在 main.uts 中调用 createPinia() 并 app.use(pinia)')
}
const activePinia = pinia!
// 同 id 复用:直接返回缓存(关键:保证跨页面是同一个实例)
const cached = activePinia._stores.get(id)
if (cached != null) {
console.log('[x-pinia-s] reuse cached store:', id)
return cached as any as T
}
console.log('[x-pinia-s] create new store:', id)
// 首次创建:通过 pinia._e.run() 切换到 Pinia 顶层 scope,再创建 store 子 scope
// 这样:
// - store 子 scope 嵌套在 pinia._e(顶层 scope)下,不被组件 scope 捕获
// - 组件销毁时只销毁组件 scope,pinia._e 与 store 子 scope 都依然活着
// - store 内 computed / watch 跨页面始终有效(这才是 Pinia 跨页面共享的真正原理)
// 用一个外部 holder 接住嵌套返回的实例(UTS 闭包对外部变量赋值需要中转 holder 对象)
const holder : Array<any> = [] as Array<any>
activePinia._e.run(() : void => {
const childScope : EffectScope = effectScope()
childScope.run(() : void => {
const created : T = factory()
const base : PiniaStoreBase = created as any as PiniaStoreBase
base._scope = childScope
base._setupBy(id, activePinia)
holder.push(created as any)
})
})
const finalInstance : T = (holder[0]) as T
// 注册到 Pinia(_stores : Map<string, any>,T 必须显式 as any)
activePinia._stores.set(id, finalInstance as any)
// 应用全部已注册插件
for (let i = 0; i < activePinia._plugins.length; i++) {
applyPluginToStore(activePinia, finalInstance as any, activePinia._plugins[i])
}
return finalInstance
}
}
/**
* 辅助工具:把 store 的状态映射到组件 computed
*
* 仅提供 `mapState` / `mapStateMapped`,**不提供 mapActions** —
* UTS 严格类型不允许从 any 动态 cast 为函数类型并调用,
* Options API 中的 actions 直接手写代理即可(一行代码):
*
* @example
* ```uvue
* <script lang="ts">
* import { mapState } from '@/uni_modules/x-pinia-s'
* import { useCounterStore } from './stores/counter'
*
* export default {
* computed: {
* ...mapState(useCounterStore, ['state', 'doubled'])
* },
* methods: {
* // actions 手写代理:一行一个,类型完全保留
* increment() : void { useCounterStore().increment() },
* setName(n : string) : void { useCounterStore().setName(n) }
* }
* }
* </script>
* ```
*
* 在组合式 API(<script setup>)中无需 mapHelpers,直接用 useStore() 即可。
*/
/**
* 把 store 的字段映射成 computed 形式的对象。
* 返回一个 UTSJSONObject,每个 key 对应一个 () => any 的 getter 函数。
*/
export function mapState<T>(useStore : () => T, keys : Array<string>) : UTSJSONObject {
const result : UTSJSONObject = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
result[key] = () : any => {
const store = useStore() as any as UTSJSONObject
return store[key]
}
}
return result
}
/**
* 同 mapState,但允许通过 mapping 对象自定义 key 名映射:
*
* ```uts
* mapStateMapped(useUserStore, { userName: 'name', userAge: 'age' })
* ```
*/
export function mapStateMapped<T>(useStore : () => T, mapping : UTSJSONObject) : UTSJSONObject {
const result : UTSJSONObject = {}
UTSJSONObject.keys(mapping).forEach((aliasKey : string) : void => {
const realKey = mapping[aliasKey] as string
result[aliasKey] = () : any => {
const store = useStore() as any as UTSJSONObject
return store[realKey]
}
})
return result
}
/**
* 持久化插件
*
* 自动把 store.$state 同步到 uni.setStorageSync,下次启动时还原。
* 通过 pinia.use(createPersistPlugin({...})) 启用。
*
* @example
* ```uts
* const pinia = createPinia()
* pinia.use(createPersistPlugin({
* keyPrefix: 'pinia:',
* includeStores: ['user', 'app'], // 仅持久化指定 store
* excludeStores: [],
* serializer: null
* } as PersistOptions))
* ```
*/
import {
PiniaPlugin,
PiniaPluginContext,
PersistOptions,
PersistSerializer,
SubscriptionMutation
} from './types.uts'
import { PiniaStoreBase } from './storeBase.uts'
/** 默认 JSON 序列化器 */
const defaultSerializer : PersistSerializer = {
serialize: (state : UTSJSONObject) : string => {
const s = JSON.stringify(state)
return s == null ? '{}' : s!
},
deserialize: (raw : string) : UTSJSONObject => {
if (raw == '') return ({} as UTSJSONObject)
const parsed = JSON.parseObject(raw)
if (parsed == null) return ({} as UTSJSONObject)
return parsed!
}
}
/** 默认配置 */
function mergePersistOptions(opts : PersistOptions | null) : PersistOptions {
const defaults : PersistOptions = {
keyPrefix: 'pinia:',
includeStores: null,
excludeStores: [],
serializer: null
}
if (opts == null) return defaults
const o = opts!
return {
keyPrefix: o.keyPrefix,
includeStores: o.includeStores,
excludeStores: o.excludeStores,
serializer: o.serializer
} as PersistOptions
}
/** 判断某个 store id 是否应该被持久化 */
function shouldPersist(storeId : string, opts : PersistOptions) : boolean {
// 黑名单优先(包含即排除)
for (let i = 0; i < opts.excludeStores.length; i++) {
if (opts.excludeStores[i] == storeId) return false
}
if (opts.includeStores == null) return true
const list = opts.includeStores!
for (let i = 0; i < list.length; i++) {
if (list[i] == storeId) return true
}
return false
}
/**
* 创建持久化插件
*
* @param opts 配置;传 null 使用默认值
*/
export function createPersistPlugin(opts : PersistOptions | null) : PiniaPlugin {
const config = mergePersistOptions(opts)
const serializer = config.serializer == null ? defaultSerializer : config.serializer!
const plugin : PiniaPlugin = (ctx : PiniaPluginContext) : void => {
const id = ctx.storeId
if (!shouldPersist(id, config)) return
const storageKey = config.keyPrefix + id
const storeBase : PiniaStoreBase = ctx.store as any as PiniaStoreBase
// 1. 启动时还原:把 storage 里的 JSON 转 UTSJSONObject 后交给子类的 _hydrate 装载
try {
const raw = uni.getStorageSync(storageKey)
if (raw != null && typeof raw == 'string' && (raw as string) != '') {
const restored = serializer.deserialize(raw as string)
storeBase._hydrate(restored)
}
} catch (e) {
console.warn('[x-pinia-s][persist] restore failed for ' + id + ':', e)
}
// 2. 订阅状态变更,写回 storage
// state 参数已是 storeBase._serialize() 的结果(由 PiniaStoreBase 内部分发)
storeBase.$subscribe((_mutation : SubscriptionMutation, state : UTSJSONObject) : void => {
try {
const str = serializer.serialize(state)
uni.setStorageSync(storageKey, str)
} catch (e) {
console.warn('[x-pinia-s][persist] save failed for ' + id + ':', e)
}
})
}
return plugin
}
/**
* 手动清空某个 store 的持久化数据(不影响内存中的状态)
*
* @param storeId store id
* @param keyPrefix storage key 前缀,需要与 createPersistPlugin 时使用的一致
*/
export function clearPersistedState(storeId : string, keyPrefix : string) : void {
try {
uni.removeStorageSync(keyPrefix + storeId)
} catch (e) {
console.warn('[x-pinia-s][persist] clear failed for ' + storeId + ':', e)
}
}
/**
* activePinia 全局状态管理
*
* 当前活动的 Pinia 实例。defineStore 返回的 useStore 函数在调用时
* 会从这里获取当前 Pinia 实例,没有则报错。
*/
import { IPinia } from './types.uts'
let _activePinia : IPinia | null = null
/**
* 设置当前活动的 Pinia 实例。
* 通常由 createPinia() 自动调用一次;多 Pinia 实例场景可手动切换。
*/
export function setActivePinia(pinia : IPinia | null) : void {
_activePinia = pinia
}
/**
* 获取当前活动的 Pinia 实例。
* 若未调用 createPinia() 则返回 null,调用方应自行报错。
*/
export function getActivePinia() : IPinia | null {
return _activePinia
}
/**
* PiniaStoreBase
*
* 用户继承本类来定义 store。基类提供 $id / $state / $subscribe / $onAction / $dispose
* 等核心能力;$reset / $patch / 持久化 这种依赖 "框架自动操作 state 字段" 的功能,
* 由于 UTS 没有 Proxy 也无法把 reactive 对象 cast 为 UTSJSONObject,
* 改为 **Template Method 模式**:子类按需重写 `_doReset` / `_hydrate` / `_serialize`。
*
* @example
* ```uts
* type CounterState = { count : number, name : string }
*
* export class CounterStore extends PiniaStoreBase {
* state : CounterState = reactive<CounterState>({ count: 0, name: '' })
*
* constructor() {
* super()
* this.bindState(this.state)
* }
*
* // actions = 普通 method
* increment() : void { this.state.count++ }
* setName(n : string) : void { this.state.name = n }
*
* // 想要 $reset 工作?重写 _doReset
* override _doReset() : void {
* this.state.count = 0
* this.state.name = ''
* }
*
* // 想要 $patch 或持久化工作?重写 _hydrate + _serialize
* override _hydrate(data : UTSJSONObject) : void {
* if (data['count'] != null) this.state.count = data['count'] as number
* if (data['name'] != null) this.state.name = data['name'] as string
* }
*
* override _serialize() : UTSJSONObject {
* return { count: this.state.count, name: this.state.name } as UTSJSONObject
* }
* }
* ```
*
* @author tmui4x
* @copyright https://tmui.design
*/
import {
IPinia,
SubscriptionMutation,
StateSubscriptionCallback,
ActionSubscriptionCallback,
ActionContext,
UnsubscribeFn
} from './types.uts'
import { StateSubscriptionList, ActionSubscriptionList, ActionTriggerResult } from './subscriptions.uts'
export class PiniaStoreBase {
/** store 唯一 id(由 defineStore 注入;用户不要手动赋值) */
$id : string = ''
// ============ 内部字段 ============
/** 用户绑定的 state 引用(任意类型,通常是 reactive(...)) */
protected _state : any | null = null
/** 状态订阅集合 */
protected _stateSubs : StateSubscriptionList = new StateSubscriptionList()
/** action 订阅集合 */
protected _actionSubs : ActionSubscriptionList = new ActionSubscriptionList()
/** watch 停止函数 */
protected _watchStopper : (() => void) | null = null
/** 所属 Pinia 实例(由 _setupBy 注入) */
protected _pinia : IPinia | null = null
/** 是否已绑定过 state */
protected _bound : boolean = false
/**
* effect 作用域(由 defineStore 在 new XxxStore() 之前注入)。
* store 内所有的 computed / watch 都绑定到本 scope,不会被外层组件销毁影响 ——
* 这样跨页面共享 store 时(返回上页 → 再进入),computed 仍然有效。
*/
_scope : EffectScope | null = null
constructor() { }
/** 当前 state 引用(与子类的 state 字段是同一对象;可能为 null,子类未调用 bindState 时) */
get $state() : any | null {
return this._state
}
// ============ 子类必调工具 ============
/**
* 绑定状态。子类必须在 constructor 中调用一次:
* ```uts
* constructor() {
* super()
* this.bindState(this.state) // this.state 是子类自己声明的 reactive 对象
* }
* ```
*
* 入参类型为 any —— UTS 名义类型系统下,用户的 state 类型 (reactive<T>) 与
* 任何系统类型都不兼容;用 any 让调用方无需 cast,且内部不再尝试转 UTSJSONObject
* (以前的 `state as any as UTSJSONObject` 会在运行时抛 ClassCastException)。
*/
protected bindState(state : any) : void {
if (this._bound) {
console.warn('[x-pinia-s][' + this.$id + '] bindState 只能调用一次')
return
}
this._bound = true
this._state = state
}
// ============ 可重写的 Template Method(按需重写) ============
/**
* 子类重写:定义 `$reset()` 时如何把 state 设回初始值。
* 默认空实现 —— 不重写则 `$reset()` 是 no-op(仅触发订阅器)。
*/
_doReset() : void { }
/**
* 子类重写:把外部 UTSJSONObject 数据装载到 state。
* - `$patch(partial)` 调用本方法
* - 持久化插件启动恢复时调用本方法
*
* 实现时建议判断字段是否存在,再赋值,以兼容 partial:
* ```uts
* if (data['count'] != null) this.state.count = data['count'] as number
* ```
*
* 默认空实现 —— 不重写则 `$patch()` 和持久化恢复都是 no-op。
*/
_hydrate(_data : UTSJSONObject) : void { }
/**
* 子类重写:把 state 序列化为 UTSJSONObject。
* - 状态变更订阅($subscribe)回调用本方法生成 state 视图
* - 持久化插件保存时调用本方法
*
* 默认返回空对象 —— 不重写则订阅器收到的 state 永远是 `{}`,持久化也无意义。
*/
_serialize() : UTSJSONObject {
return ({} as UTSJSONObject)
}
// ============ Action 包装(可选) ============
/**
* 让某个 action 触发 $onAction 订阅器。普通 action 直接写 method 即可,
* 仅在主动想被 $onAction 追踪时才包装。
*/
protected callAction(name : string, fn : () => any) : any | null {
return this._invokeAction(name, fn, [] as Array<any>)
}
/**
* 同 callAction,但额外把参数列表上报给订阅器。
*/
protected callActionWithArgs(name : string, fn : () => any, args : Array<any>) : any | null {
return this._invokeAction(name, fn, args)
}
/** 内部 action 执行器 */
private _invokeAction(name : string, fn : () => any, args : Array<any>) : any | null {
const actionCtx : ActionContext = {
name: name,
storeId: this.$id,
args: args
}
const triggerResult : ActionTriggerResult = this._actionSubs.trigger(actionCtx)
let result : any | null = null
try {
result = fn()
} catch (e) {
for (let i = 0; i < triggerResult.errorList.length; i++) {
try {
triggerResult.errorList[i](e)
} catch (e2) {
console.warn('[x-pinia-s][' + this.$id + '] onError callback error:', e2)
}
}
throw e
}
for (let i = 0; i < triggerResult.afterList.length; i++) {
try {
triggerResult.afterList[i](result)
} catch (e3) {
console.warn('[x-pinia-s][' + this.$id + '] after callback error:', e3)
}
}
return result
}
// ============ 公共方法 ============
/** 浅合并 partial 到 state(依赖子类的 _hydrate 实现) */
$patch(partial : UTSJSONObject) : void {
this._hydrate(partial)
const m : SubscriptionMutation = {
type: 'patch object',
storeId: this.$id,
payload: partial,
timestamp: Date.now()
}
const snapshot : UTSJSONObject = this._serialize()
this._stateSubs.trigger(m, snapshot)
if (this._pinia != null) {
this._pinia!.state[this.$id] = snapshot
}
}
/** 重置 state 到初始值(依赖子类的 _doReset 实现) */
$reset() : void {
this._doReset()
const m : SubscriptionMutation = {
type: 'reset',
storeId: this.$id,
payload: null,
timestamp: Date.now()
}
const snapshot : UTSJSONObject = this._serialize()
this._stateSubs.trigger(m, snapshot)
if (this._pinia != null) {
this._pinia!.state[this.$id] = snapshot
}
}
/** 订阅状态变更,返回取消订阅函数 */
$subscribe(cb : StateSubscriptionCallback) : UnsubscribeFn {
return this._stateSubs.add(cb)
}
/** 订阅 action 调用,返回取消订阅函数 */
$onAction(cb : ActionSubscriptionCallback) : UnsubscribeFn {
return this._actionSubs.add(cb)
}
/** 销毁 store:停止 watch、清空订阅、停止 effect 作用域、从 Pinia 注册表移除 */
$dispose() : void {
if (this._watchStopper != null) {
try {
this._watchStopper!()
} catch (e) {
console.warn('[x-pinia-s][' + this.$id + '] watch stop error:', e)
}
this._watchStopper = null
}
this._stateSubs.clear()
this._actionSubs.clear()
// 停止 effect 作用域:清理 store 内所有 computed / watch
if (this._scope != null) {
try {
this._scope!.stop()
} catch (e) {
console.warn('[x-pinia-s][' + this.$id + '] scope stop error:', e)
}
this._scope = null
}
if (this._pinia != null) {
this._pinia!._stores.delete(this.$id)
}
}
// ============ 内部初始化(由 defineStore 调用) ============
/**
* 由 defineStore 调用,注入 id、pinia、启动 watch。
* @internal 用户代码不要调用本方法。
*/
_setupBy(id : string, pinia : IPinia) : void {
this.$id = id
this._pinia = pinia
// 监听 state 引用变化(deep)
if (this._state != null) {
const stateRef : any = this._state! // null 检查后用 ! 断言为非空
const sl : StateSubscriptionList = this._stateSubs
const sid : string = id
const piniaRef : IPinia = pinia
const selfRef : PiniaStoreBase = this
this._watchStopper = watch(() : any => stateRef, () : void => {
const m : SubscriptionMutation = {
type: 'direct',
storeId: sid,
payload: null,
timestamp: Date.now()
}
const snapshot : UTSJSONObject = selfRef._serialize()
sl.trigger(m, snapshot)
piniaRef.state[sid] = snapshot
}, { deep: true })
}
// 初始化 pinia.state[id] = 当前序列化结果(可能是 {})
pinia.state[id] = this._serialize()
}
}
/**
* 订阅器管理
*
* 提供两类订阅器集合:
* - StateSubscriptionList:状态变更订阅($subscribe)
* - ActionSubscriptionList:action 调用订阅($onAction)
*
* UTS 中函数引用比较没有 === ,使用 indexOf 移除。
*/
import {
StateSubscriptionCallback,
SubscriptionMutation,
ActionSubscriptionCallback,
ActionContext,
AfterActionCallback,
OnErrorActionCallback,
UnsubscribeFn
} from './types.uts'
/** 状态订阅集合 */
export class StateSubscriptionList {
private _list : Array<StateSubscriptionCallback> = []
/**
* 添加订阅,返回取消订阅函数
*/
add(cb : StateSubscriptionCallback) : UnsubscribeFn {
this._list.push(cb)
return () : void => {
this.remove(cb)
}
}
/** 移除某个订阅 */
remove(cb : StateSubscriptionCallback) : void {
const idx = this._list.indexOf(cb)
if (idx >= 0) {
this._list.splice(idx, 1)
}
}
/** 触发所有订阅 */
trigger(mutation : SubscriptionMutation, state : UTSJSONObject) : void {
// 拷贝一份再遍历,避免回调中修改订阅列表导致跳过
const snapshot : Array<StateSubscriptionCallback> = []
for (let i = 0; i < this._list.length; i++) {
snapshot.push(this._list[i])
}
for (let i = 0; i < snapshot.length; i++) {
try {
snapshot[i](mutation, state)
} catch (e) {
console.warn('[x-pinia-s] state subscription error:', e)
}
}
}
/** 清空全部订阅 */
clear() : void {
this._list = []
}
/** 当前订阅数量 */
size() : number {
return this._list.length
}
}
/** Action 订阅集合 */
export class ActionSubscriptionList {
private _list : Array<ActionSubscriptionCallback> = []
/**
* 添加 action 订阅,返回取消订阅函数
*/
add(cb : ActionSubscriptionCallback) : UnsubscribeFn {
this._list.push(cb)
return () : void => {
this.remove(cb)
}
}
/** 移除某个订阅 */
remove(cb : ActionSubscriptionCallback) : void {
const idx = this._list.indexOf(cb)
if (idx >= 0) {
this._list.splice(idx, 1)
}
}
/**
* 触发 action 订阅。
* 调用方负责调用真实 action 并通过 afterCallbacks/errorCallbacks 反馈结果。
*
* @returns 收集到的 after / onError 回调数组(由调用方在 action 完成后逐一调用)
*/
trigger(ctx : ActionContext) : ActionTriggerResult {
const afterList : Array<AfterActionCallback> = []
const errorList : Array<OnErrorActionCallback> = []
const after = (cb : AfterActionCallback) : void => {
afterList.push(cb)
}
const onError = (cb : OnErrorActionCallback) : void => {
errorList.push(cb)
}
// 拷贝快照,避免迭代中变更
const snapshot : Array<ActionSubscriptionCallback> = []
for (let i = 0; i < this._list.length; i++) {
snapshot.push(this._list[i])
}
for (let i = 0; i < snapshot.length; i++) {
try {
snapshot[i](ctx, after, onError)
} catch (e) {
console.warn('[x-pinia-s] action subscription error:', e)
}
}
return {
afterList: afterList,
errorList: errorList
} as ActionTriggerResult
}
/** 清空 */
clear() : void {
this._list = []
}
/** 当前订阅数量 */
size() : number {
return this._list.length
}
}
/** Action 触发返回结构 */
export type ActionTriggerResult = {
afterList : Array<AfterActionCallback>,
errorList : Array<OnErrorActionCallback>
}
/**
* x-pinia-s 类型定义
*
* UTS 严格类型版 Pinia for uni-app-x(class extends 风格)
*
* @author tmui4x
* @copyright https://tmui.design
*/
// ============ 基础类型 ============
/** 取消订阅函数 */
export type UnsubscribeFn = () => void
/** 状态变更类型 */
export type SubscriptionMutationType = 'direct' | 'patch object' | 'patch function' | 'reset'
/** 状态变更信息($subscribe 回调参数) */
export type SubscriptionMutation = {
/** 变更类型 */
type : SubscriptionMutationType,
/** 触发变更的 store id */
storeId : string,
/** 当 type 为 patch object 时为传入的 partial 对象 */
payload : UTSJSONObject | null,
/** 变更发生的时间戳 */
timestamp : number
}
/** 状态订阅回调 */
export type StateSubscriptionCallback = (mutation : SubscriptionMutation, state : UTSJSONObject) => void
/** Action 调用信息($onAction 回调参数) */
export type ActionContext = {
/** action 名 */
name : string,
/** 所属 store id */
storeId : string,
/** 调用参数 */
args : Array<any>
}
/** action 完成后回调 */
export type AfterActionCallback = (result : any) => void
/** action 异常回调 */
export type OnErrorActionCallback = (error : any) => void
/** Action 订阅回调 */
export type ActionSubscriptionCallback = (
ctx : ActionContext,
after : (cb : AfterActionCallback) => void,
onError : (cb : OnErrorActionCallback) => void
) => void
// ============ Pinia 插件 ============
/**
* Pinia 插件上下文。
*
* `store` / `state` 字段都用 `any` —— UTS 名义类型系统下,用户的 reactive state
* 是 ReactiveObject 强类型 class(不是 UTSJSONObject),无法 cast。
* 插件需要 store 的方法时,在插件文件中 `import { PiniaStoreBase }` 然后 cast。
* 插件需要序列化 state 时,调用 `(ctx.store as any as PiniaStoreBase)._serialize()`。
*/
export type PiniaPluginContext = {
/** Pinia 实例 */
pinia : IPinia,
/** 当前 store id */
storeId : string,
/** 当前 store 实例(实际类型为 PiniaStoreBase 子类,按 any 暴露) */
store : any,
/** 当前 store 的 state 引用(用户 reactive 对象,按 any 暴露) */
state : any
}
/**
* Pinia 插件类型。
*
* 与原版 Pinia 不同:UTS 严格类型不允许向 class 实例动态注入属性,
* 因此插件**不能返回扩展对象**。插件应通过 `ctx.store.$subscribe` / `ctx.store.$onAction`
* 等 hook 完成所有逻辑(监听、记录、持久化等)。
*/
export type PiniaPlugin = (ctx : PiniaPluginContext) => void
// ============ Pinia 实例 ============
/**
* Pinia 实例接口。
*
* `_stores` 字段类型为 `Map<string, any>` —— 同样为避免循环依赖;
* 实际存储的是 PiniaStoreBase 的子类实例。
*
* 重要:install / use 必须用「方法语法」而非「字段语法」声明。
* UTS 转 Kotlin 后,字段语法 `install : (...) => void` 会被当成 property(需用字段初始化器实现),
* 方法语法 `install(...) : void` 才会被当成可 override 的 method。
*/
export interface IPinia {
/** 全部 store 状态合集(id -> state),供持久化等场景使用 */
state : UTSJSONObject
/** 内部:已实例化的 store 集合(值为 PiniaStoreBase 子类实例) */
_stores : Map<string, any>
/** 内部:插件列表 */
_plugins : Array<PiniaPlugin>
/**
* 内部:Pinia 顶层 effect 作用域。
* 在 `createPinia()` 中创建(必须在 main.uts 顶层调用,确保 currentScope 为 null
* 时创建出一个不依附任何组件的顶层 scope)。
* 每个 store 创建时通过 `_e.run(() => effectScope())` 创建子 scope —— 子 scope 嵌套在
* Pinia 顶层 scope 下,不会被外层组件 scope 捕获;组件销毁不影响 store 内的 effects。
*/
_e : EffectScope
/** Vue 插件 install 方法(app.use(pinia) 时调用) */
install(app : VueApp) : void;
/** 注册插件,返回自身以便链式调用 */
use(plugin : PiniaPlugin) : IPinia;
}
// ============ 持久化插件 ============
/** 持久化序列化器 */
export type PersistSerializer = {
serialize : (state : UTSJSONObject) => string,
deserialize : (raw : string) => UTSJSONObject
}
/** 持久化插件配置 */
export type PersistOptions = {
/** 自定义 storage key 前缀,默认 'pinia:' */
keyPrefix : string,
/** 是否仅持久化指定的 store id(白名单),为 null 表示全部持久化 */
includeStores : Array<string> | null,
/** 黑名单 store id(优先级高于 includeStores) */
excludeStores : Array<string>,
/** 自定义序列化器,为 null 时使用 JSON */
serializer : PersistSerializer | null
}
{
"id": "x-pinia-s",
"displayName": "Pinia by uts",
"version": "1.0.0",
"description": "uni-app-x Pinia,仅Setup Store 风格,提供 / 插件系统 / 持久化",
"keywords": [
"pinia",
"store",
"状态管理",
"uts",
"数据持久化"
],
"repository": "",
"engines": {
"HBuilderX": "^3.6.8",
"uni-app": "",
"uni-app-x": "^4.87"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "",
"darkmode": "√",
"i18n": "√",
"widescreen": "√"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "x",
"aliyun": "x",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "-",
"vue3": "-"
},
"web": {
"safari": "-",
"chrome": "-"
},
"app": {
"vue": "-",
"nvue": "-",
"android": "-",
"ios": "-",
"harmony": "-"
},
"mp": {
"weixin": "-",
"alipay": "-",
"toutiao": "-",
"baidu": "-",
"kuaishou": "-",
"jd": "-",
"harmony": "-",
"qq": "-",
"lark": "-"
},
"quickapp": {
"huawei": "-",
"union": "-"
}
},
"uni-app-x": {
"web": {
"safari": {
"extVersion": "1.0.0",
"minVersion": ""
},
"chrome": {
"extVersion": "1.0.0",
"minVersion": "94"
}
},
"app": {
"android": {
"extVersion": "1.0.0",
"minVersion": "21"
},
"ios": {
"extVersion": "1.0.0",
"minVersion": "12"
},
"harmony": {
"extVersion": "1.0.0",
"minVersion": "12"
}
},
"mp": {
"weixin": {
"extVersion": "1.0.0",
"minVersion": "3.0.0"
}
}
}
}
}
}
}
\ No newline at end of file \ No newline at end of file
{
"minSdkVersion": "21"
}
\ No newline at end of file \ No newline at end of file
{
"dependencies": {
}
}
\ No newline at end of file \ No newline at end of file
import { store } from "@/store/index.uts"; import { pinia } from "@/store/index.uts";
import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts"; import { applyScreenOrientationLock } from "@/utils/apply-orientation-lock.uts";
import { updateOrientation } from '@/services/adapter/hooks/index.uts' import { updateOrientation } from '@/services/adapter/hooks/index.uts'
export function appMixin(app: VueApp) { export function appMixin(app: VueApp) {
// 注入 $store,兼容旧项目 this.$store 用法 // 注入 $store,兼容旧项目 this.$store 用法
app.config.globalProperties.$store = store; app.config.globalProperties.$pinia = pinia;
app.mixin({ app.mixin({
onPageScroll(e) { onPageScroll(e) {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!