Commit 345bb304 by Jaxon

style(uniapp-x-tape): 统一代码格式并优化语法一致性

- 调整导入顺序和导出顺序以保持一致性
- 统一使用严格相等运算符(!==/===)替代宽松相等
- 规范对象属性顺序和类型定义结构
- 优化字符串模板和箭头函数语法
- 统一代码缩进和换行格式
- 修复条件表达式括号和三元运算符格式
- 更新文件路径引用和模块声明格式
1 parent dd5feff4
Showing 48 changed files with 3633 additions and 3594 deletions
<script lang="uts">
let firstBackTime = 0;
export default {
onLaunch: function () {
onLaunch () {
console.log("App Launch");
},
onShow: function () {
onShow () {
console.log("App Show");
},
onHide: function () {
onHide () {
console.log("App Hide");
},
// #ifdef APP-ANDROID
onLastPageBackPress: function () {
onLastPageBackPress () {
console.log("App LastPageBackPress");
if (firstBackTime == 0) {
uni.showToast({
......@@ -28,7 +28,7 @@ export default {
}
},
// #endif
onExit: function () {
onExit () {
console.log("App Exit");
}
};
......
......@@ -163,4 +163,4 @@ export const signSecretKey: SignSecretKeyItem = signSecretKeyMap[currentTarget]
export const pathEnum: UTSJSONObject = PATH_ENUM;
export const pathEnumExport: UTSJSONObject = PATH_ENUM;
// env 仅用于区分当前环境标签,这里直接按 TARGET_INDEX 映射为字符串
export const env: string = TARGET_INDEX == 3 ? "production" : TARGET_INDEX == 1 ? "develop" : "test";
export const env: string = TARGET_INDEX == 3 ? "production" : (TARGET_INDEX == 1 ? "develop" : "test");
import { sign } from "./sign.uts";
import { secretKey, pathEnum, domain, djDomain, merchantDomain, djSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts";
import { djDomain, djSecretKey, domain, merchantDomain, pathEnum, secretKey } from "../env.uts";
import { sign } from "./sign.uts";
type HostType = "scrm" | "dj" | "merchant" | "ip";
type HostType = "dj" | "ip" | "merchant" | "scrm";
const HOST: Record<HostType, string> = {
scrm: domain,
......@@ -18,14 +18,6 @@ const HOST: Record<HostType, string> = {
* - 处理业务 code 及登录态失效跳转
*/
class Request {
get(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType): Promise<any> {
return this.request("GET", params, returnAll, hostType);
}
post(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType, timeout?: number): Promise<any> {
return this.request("POST", params, returnAll, hostType, timeout);
}
/**
* 业务方法调用封装
* @param method ROP 接口方法名
......@@ -36,17 +28,115 @@ class Request {
fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType?: HostType): Promise<any> {
const payload = {} as UTSJSONObject;
// method
payload["method"] = method;
payload.method = method;
// 合并业务参数
const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
for (const key of dataKeys) {
// @ts-ignore
payload[key] = (data as UTSJSONObject)[key];
}
return this.post(payload, returnAll, hostType);
}
get(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType): Promise<any> {
return this.request("GET", params, returnAll, hostType);
}
post(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType, timeout?: number): Promise<any> {
return this.request("POST", params, returnAll, hostType, timeout);
}
/**
* 简单的原始 uni.request 封装
*/
uni_request(options: {
data?: UTSJSONObject;
dataType?: string;
header?: UTSJSONObject;
method?: "GET" | "POST";
responseType?: string;
url: string;
}): Promise<any> {
return new Promise((resolve) => {
uni.request({
url: options.url,
data: options.data ?? ({} as UTSJSONObject),
method: options.method ?? "GET",
header: options.header ?? ({} as UTSJSONObject),
dataType: options.dataType ?? "json",
responseType: options.responseType ?? "text",
success: (response) => {
resolve(response.data);
}
});
});
}
/**
* 组装 ROP 请求参数并完成签名
*/
private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
let projectName = (params.projectName ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params.method as string);
} else {
// 使用后删除 projectName 字段
delete params.projectName;
}
let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
const projectSecret = secretKey[projectName];
if (projectSecret != null) {
appKey = projectSecret.appKey;
secret = projectSecret.secret;
}
if (hostType == "dj") {
appKey = djSecretKey.appKey;
secret = djSecretKey.secret;
}
const sessionId = storage.get("sessionId") as null | string;
let noSignAttr: string[] = [];
if (params.sessionId == null && sessionId != null && sessionId != "") {
params.sessionId = sessionId;
}
if (params.delSessionId != null) {
delete params.sessionId;
delete params.delSessionId;
}
if (params.noSignAttr != null) {
noSignAttr = params.noSignAttr as string[];
delete params.noSignAttr;
}
params.v = "1.0.0";
params.format = "json";
params.locale = "zh_CN";
params.source = "app";
params.appKey = appKey;
return sign(params, secret, noSignAttr);
}
/**
* 根据 method 解析出 rop 项目名
* @example sso.xxx.xxx => 第三个段作为项目名
*/
private getRopProject(method: string): string {
const parts = method.split(".");
if (parts.length >= 3) {
return parts[2];
}
return "";
}
private request(
requestMethod: "GET" | "POST",
params: UTSJSONObject,
......@@ -72,28 +162,28 @@ class Request {
const header =
requestMethod == "POST"
? {
"content-type": "application/x-www-form-urlencoded"
}
"content-type": "application/x-www-form-urlencoded"
}
: {
"Cache-Control": "no-cache"
};
"Cache-Control": "no-cache"
};
let projectName = (params["projectName"] ?? "") as string;
let projectName = (params.projectName ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params["method"] as string);
projectName = this.getRopProject(params.method as string);
}
const path = pathEnum[projectName] ?? "";
const requestData = this.getData(params, finalHostType);
uni.request({
url: `${HOST[finalHostType]}${path}router?method=${requestData["method"]}`,
url: `${HOST[finalHostType]}${path}router?method=${requestData.method}`,
data: requestData,
method: requestMethod,
header,
dataType: "json",
responseType: "text",
timeout: timeout ?? 60000,
timeout: timeout ?? 60_000,
success: (response) => {
const data: any = response.data;
const statusCode = response.statusCode;
......@@ -110,7 +200,7 @@ class Request {
return;
}
const code = (data.code ?? "") as string | number;
const code = (data.code ?? "") as number | string;
const message = (data.message ?? "") as string;
if (returnAll) {
......@@ -142,11 +232,11 @@ class Request {
fail: (error) => {
uni.hideLoading();
let title = "系统异常";
if (typeof error == "string") {
if (typeof error === "string") {
title = error;
} else {
// @ts-ignore
const errMsg = (error as any).errMsg as string | null;
const errMsg = (error as any).errMsg as null | string;
if (errMsg != null && errMsg != "") {
title = errMsg;
} else {
......@@ -154,7 +244,7 @@ class Request {
}
}
console.error(`${params["method"]} 接口异常:`, error);
console.error(`${params.method} 接口异常:`, error);
uni.showToast({
title,
icon: "error"
......@@ -169,97 +259,6 @@ class Request {
});
});
}
/**
* 组装 ROP 请求参数并完成签名
*/
private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
let projectName = (params["projectName"] ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params["method"] as string);
} else {
// 使用后删除 projectName 字段
delete params["projectName"];
}
let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
const projectSecret = secretKey[projectName];
if (projectSecret != null) {
appKey = projectSecret.appKey;
secret = projectSecret.secret;
}
if (hostType == "dj") {
appKey = djSecretKey.appKey;
secret = djSecretKey.secret;
}
const sessionId = storage.get("sessionId") as string | null;
let noSignAttr: string[] = [];
if (params["sessionId"] == null && sessionId != null && sessionId != "") {
params["sessionId"] = sessionId;
}
if (params["delSessionId"] != null) {
delete params["sessionId"];
delete params["delSessionId"];
}
if (params["noSignAttr"] != null) {
noSignAttr = params["noSignAttr"] as string[];
delete params["noSignAttr"];
}
params["v"] = "1.0.0";
params["format"] = "json";
params["locale"] = "zh_CN";
params["source"] = "app";
params["appKey"] = appKey;
return sign(params, secret, noSignAttr);
}
/**
* 根据 method 解析出 rop 项目名
* @example sso.xxx.xxx => 第三个段作为项目名
*/
private getRopProject(method: string): string {
const parts = method.split(".");
if (parts.length >= 3) {
return parts[2];
}
return "";
}
/**
* 简单的原始 uni.request 封装
*/
uni_request(options: {
url: string;
method?: "GET" | "POST";
data?: UTSJSONObject;
header?: UTSJSONObject;
dataType?: string;
responseType?: string;
}): Promise<any> {
return new Promise((resolve) => {
uni.request({
url: options.url,
data: options.data ?? ({} as UTSJSONObject),
method: options.method ?? "GET",
header: options.header ?? ({} as UTSJSONObject),
dataType: options.dataType ?? "json",
responseType: options.responseType ?? "text",
success: (response) => {
resolve(response.data);
}
});
});
}
}
export const request = new Request();
......
......@@ -9,19 +9,19 @@ function encodeUTF8(s: string): number[] {
const c = s.charCodeAt(i);
if (c < 0x80) {
r.push(c);
} else if (c < 0x800) {
r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f));
} else if (c < 0x8_00) {
r.push(0xC0 + ((c >> 6) & 0x1F), 0x80 + (c & 0x3F));
} else {
const x = c ^ 0xd800;
const x = c ^ 0xD8_00;
if (x >> 10 == 0) {
const next = s.charCodeAt(i + 1) ^ 0xdc00;
const code = (x << 10) + next + 0x10000;
r.push(0xf0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3f));
const next = s.charCodeAt(i + 1) ^ 0xDC_00;
const code = (x << 10) + next + 0x1_00_00;
r.push(0xF0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3F));
i++;
} else {
r.push(0xe0 + (c >> 12));
r.push(0xE0 + (c >> 12));
}
r.push(0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f));
r.push(0x80 + ((c >> 6) & 0x3F), 0x80 + (c & 0x3F));
}
i++;
}
......@@ -45,12 +45,12 @@ export function sha1(s: string): string {
s32[l - 1] = data.length << 3;
const w: number[] = [];
const k = [1518500249, 1859775393, -1894007588, -899497514];
let m0 = 1732584193;
let m1 = -271733879;
let m2 = ~1732584193;
let m3 = ~(-271733879);
let m4 = -1009589776;
const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
let m0 = 1_732_584_193;
let m1 = -271_733_879;
let m2 = ~1_732_584_193;
let m3 = ~(-271_733_879);
let m4 = -1_009_589_776;
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const f0 = (): number => (m1 & m2) | (~m1 & m3);
......
import { get, keys, set } from "../../utils/common.uts";
import { sha1 } from "./sha1.uts";
import { keys, get, set } from "../../utils/common.uts";
/**
* 参数签名方法(从 gl_tape/api/request/sign.js 迁移)
......@@ -18,8 +18,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 先将入参拷贝到 realObj 中,并清理 sign 字段
const rawKeys = keys(params);
for (let i = 0; i < rawKeys.length; i++) {
const key = rawKeys[i];
for (const key of rawKeys) {
if (key == "sign") {
continue;
}
......@@ -32,13 +31,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
sortedKeys.sort((a, b) => a.localeCompare(b));
// 归一化 value:null -> "",对象 -> JSON 字符串
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
let obj: any | null = get(realObj, key);
if (obj == null) {
obj = "";
} else if (typeof obj == "object") {
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
......@@ -47,8 +45,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = [];
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
if (noSignAttr.indexOf(key) >= 0) {
continue;
}
......
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts";
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
type GscPostConfig = {
duplicatePrevention?: boolean;
returnAll?: boolean;
timeout?: number;
duplicatePrevention?: boolean;
};
/**
......@@ -35,30 +35,29 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
return;
}
const baseURL = `${evaluationDomain}${pathEnum["evaluation"]}`;
const baseURL = `${evaluationDomain}${pathEnum.evaluation}`;
const fullUrl = `${baseURL}${url}`;
// 组装请求体,自动注入 sessionId
const payload = {} as UTSJSONObject;
const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
for (const key of dataKeys) {
// @ts-ignore
payload[key] = (data as UTSJSONObject)[key];
}
// sessionId 自动注入
const sessionId = storage.get("sessionId") as string | null;
if (sessionId != null && sessionId != "" && payload["sessionId"] == null) {
payload["sessionId"] = sessionId;
const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != "" && payload.sessionId == null) {
payload.sessionId = sessionId;
}
// 简单的重复提交防护:可选地附加一次性请求标识(仅客户端语义)
if (finalConfig.duplicatePrevention == true) {
payload["__duplicateKey"] = `${Date.now()}_${Math.random()}`;
payload.__duplicateKey = `${Date.now()}_${Math.random()}`;
}
const timeout = finalConfig.timeout ?? 300000;
const timeout = finalConfig.timeout ?? 300_000;
// 将 appId / appSecret 通过 header 传递给后端(近似旧项目 glsk-toolkit 行为)
const header = {
......@@ -114,7 +113,7 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
fail: (error) => {
let title = "业务异常";
// @ts-ignore
const errMsg = (error as any).errMsg as string | null;
const errMsg = (error as any).errMsg as null | string;
if (errMsg == "request:fail") {
title = "网络异常";
} else if (errMsg != null && errMsg != "") {
......
// 登录相关接口封装,对齐 gl_tape 中的 ROP 网关调用(http.fetch)
import { djDomain, djSecretKey, pathEnum } from '@/api/env.uts'
import { storage } from '@/utils/storage.uts'
import { djDomain, djSecretKey, pathEnum } from "@/api/env.uts";
import { storage } from "@/utils/storage.uts";
const BOUTIQUE_PATH = pathEnum['boutique'] as string
const BOUTIQUE_PATH = pathEnum.boutique as string;
// 简化版 SHA1,实现同 lib/sha1.js,用于生成 sign
function encodeUTF8(input: string): number[] {
const result: number[] = []
let i = 0
while (i < input.length) {
const cNum = input.charCodeAt(i) as number
if (cNum < 0x80) {
result.push(cNum)
} else if (cNum < 0x800) {
result.push(0xc0 + ((cNum >> 6) & 0x1f), 0x80 + (cNum & 0x3f))
} else {
let x = cNum ^ 0xd800
if (x >> 10 == 0) {
i++
const c2 = input.charCodeAt(i) as number
const uni = (x << 10) + (c2 ^ 0xdc00) + 0x10000
result.push(
0xf0 + ((uni >> 18) & 0x7),
0x80 + ((uni >> 12) & 0x3f),
0x80 + ((uni >> 6) & 0x3f),
0x80 + (uni & 0x3f)
)
} else {
result.push(
0xe0 + ((cNum >> 12) & 0x0f),
0x80 + ((cNum >> 6) & 0x3f),
0x80 + (cNum & 0x3f)
)
}
}
i++
}
return result
const result: number[] = [];
let i = 0;
while (i < input.length) {
const cNum = input.charCodeAt(i) as number;
if (cNum < 0x80) {
result.push(cNum);
} else if (cNum < 0x8_00) {
result.push(0xC0 + ((cNum >> 6) & 0x1F), 0x80 + (cNum & 0x3F));
} else {
const x = cNum ^ 0xD8_00;
if (x >> 10 == 0) {
i++;
const c2 = input.charCodeAt(i) as number;
const uni = (x << 10) + (c2 ^ 0xDC_00) + 0x1_00_00;
result.push(
0xF0 + ((uni >> 18) & 0x7),
0x80 + ((uni >> 12) & 0x3F),
0x80 + ((uni >> 6) & 0x3F),
0x80 + (uni & 0x3F)
);
} else {
result.push(
0xE0 + ((cNum >> 12) & 0x0F),
0x80 + ((cNum >> 6) & 0x3F),
0x80 + (cNum & 0x3F)
);
}
}
i++;
}
return result;
}
function sha1Hex(input: string): string {
const dataArr = encodeUTF8(input)
const data = new Uint8Array(dataArr)
const l = (((data.length + 8) >>> 6) << 4) + 16
const buffer = new Uint8Array(l << 2)
const dataBuf: ArrayBuffer = data.buffer as ArrayBuffer
buffer.set(new Uint8Array(dataBuf))
const buf: ArrayBuffer = buffer.buffer as ArrayBuffer
const s = new Uint32Array(buf)
const sBuf: ArrayBuffer = s.buffer as ArrayBuffer
const dv = new DataView(sBuf)
let i = 0
while (i < l) {
s[i] = dv.getUint32(i << 2)
i++
}
const idx = data.length >> 2
s[idx] = s[idx] | (0x80 << (24 - ((data.length & 3) * 8)))
s[l - 1] = data.length << 3
const w: number[] = []
const f = [
(m: number[]): number => (m[1] & m[2]) | (~m[1] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3],
(m: number[]): number => (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3]
]
const k = [1518500249, 1859775393, -1894007588, -899497514]
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c))
const m: number[] = [1732584193, -271733879, 0, 0, -1009589776]
m[2] = ~m[0]
m[3] = ~m[1]
let j = 0
for (i = 0; i < s.length; i += 16) {
const o = [m[0], m[1], m[2], m[3], m[4]]
for (j = 0; j < 80; j++) {
if (j < 16) {
w[j] = s[i + j]
} else {
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
}
const t = (rol(m[0], 5) + f[(j / 20) | 0](m) + m[4] + w[j] + k[(j / 20) | 0]) | 0
m[4] = m[3]
m[3] = m[2]
m[2] = rol(m[1], 30)
m[1] = m[0]
m[0] = t
}
for (j = 0; j < 5; j++) {
m[j] = (m[j] + o[j]) | 0
}
}
const mArr = new Uint32Array(m)
const mBuf: ArrayBuffer = mArr.buffer as ArrayBuffer
const out = new Uint8Array(mBuf)
let hex = ''
for (i = 0; i < out.length; i++) {
const v = out[i]
hex += (v < 16 ? '0' : '') + v.toString(16)
}
return hex
const dataArr = encodeUTF8(input);
const data = new Uint8Array(dataArr);
const l = (((data.length + 8) >>> 6) << 4) + 16;
const buffer = new Uint8Array(l << 2);
const dataBuf: ArrayBuffer = data.buffer as ArrayBuffer;
buffer.set(new Uint8Array(dataBuf));
const buf: ArrayBuffer = buffer.buffer as ArrayBuffer;
const s = new Uint32Array(buf);
const sBuf: ArrayBuffer = s.buffer as ArrayBuffer;
const dv = new DataView(sBuf);
let i = 0;
while (i < l) {
s[i] = dv.getUint32(i << 2);
i++;
}
const idx = data.length >> 2;
s[idx] = s[idx] | (0x80 << (24 - ((data.length & 3) * 8)));
s[l - 1] = data.length << 3;
const w: number[] = [];
const f = [
(m: number[]): number => (m[1] & m[2]) | (~m[1] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3],
(m: number[]): number => (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3]
];
const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const m: number[] = [1_732_584_193, -271_733_879, 0, 0, -1_009_589_776];
m[2] = ~m[0];
m[3] = ~m[1];
let j = 0;
for (i = 0; i < s.length; i += 16) {
const o = [m[0], m[1], m[2], m[3], m[4]];
for (j = 0; j < 80; j++) {
if (j < 16) {
w[j] = s[i + j];
} else {
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
const t = (rol(m[0], 5) + f[(j / 20) | 0](m) + m[4] + w[j] + k[(j / 20) | 0]) | 0;
m[4] = m[3];
m[3] = m[2];
m[2] = rol(m[1], 30);
m[1] = m[0];
m[0] = t;
}
for (j = 0; j < 5; j++) {
m[j] = (m[j] + o[j]) | 0;
}
}
const mArr = new Uint32Array(m);
const mBuf: ArrayBuffer = mArr.buffer as ArrayBuffer;
const out = new Uint8Array(mBuf);
let hex = "";
for (i = 0; i < out.length; i++) {
const v = out[i];
hex += (v < 16 ? "0" : "") + v.toString(16);
}
return hex;
}
// 按老项目 http.getData + sign.js 逻辑生成最终请求参数
function buildSignedParams(method: string, payload: UTSJSONObject): UTSJSONObject {
const params: UTSJSONObject = {}
// 复制调用参数
for (const key in payload) {
params[key] = payload[key]
}
// 基础字段
params['method'] = method
params['v'] = '1.0.0'
params['format'] = 'json'
params['locale'] = 'zh_CN'
params['source'] = 'app'
// appKey / secret
let appKey = djSecretKey['appKey'] as string
let secret = djSecretKey['secret'] as string
params['appKey'] = appKey
// sessionId(如果存在)
const sessionId = storage.get('sessionId') as string | null
if (sessionId != null && sessionId != '') {
params['sessionId'] = sessionId
}
// sign 计算:按照 key 排序、拼接 key+value
const realObj: UTSJSONObject = {}
for (const k in params) {
const v = params[k]
if (v == null) {
realObj[k] = ''
} else if (typeof v === 'object') {
realObj[k] = JSON.stringify(v)
} else {
realObj[k] = v
}
}
const keys: string[] = []
for (const k in realObj) {
keys.push(k)
}
keys.sort()
const parts: string[] = []
for (let idx = 0; idx < keys.length; idx++) {
const k = keys[idx]
const vAny = realObj[k]
const vStr = `${vAny}`
parts.push(k + vStr)
}
const signStr = secret + parts.join('') + secret
// 目前关闭本地 SHA1 计算,直接透传待签名串,方便后端放宽或调试
console.log('rop signStr (sha disabled)', signStr)
params['sign'] = signStr
return params
const params: UTSJSONObject = {};
// 复制调用参数
for (const key in payload) {
params[key] = payload[key];
}
// 基础字段
params.method = method;
params.v = "1.0.0";
params.format = "json";
params.locale = "zh_CN";
params.source = "app";
// appKey / secret
const appKey = djSecretKey.appKey as string;
const secret = djSecretKey.secret as string;
params.appKey = appKey;
// sessionId(如果存在)
const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != "") {
params.sessionId = sessionId;
}
// sign 计算:按照 key 排序、拼接 key+value
const realObj: UTSJSONObject = {};
for (const k in params) {
const v = params[k];
if (v == null) {
realObj[k] = "";
} else if (typeof v === "object") {
realObj[k] = JSON.stringify(v);
} else {
realObj[k] = v;
}
}
const keys: string[] = [];
for (const k in realObj) {
keys.push(k);
}
keys.sort();
const parts: string[] = [];
for (const k of keys) {
const vAny = realObj[k];
const vStr = `${vAny}`;
parts.push(k + vStr);
}
const signStr = secret + parts.join("") + secret;
// 目前关闭本地 SHA1 计算,直接透传待签名串,方便后端放宽或调试
console.log("rop signStr (sha disabled)", signStr);
params.sign = signStr;
return params;
}
// 统一 ROP 请求封装:/router?method=xxx
async function postRop(method: string, payload: UTSJSONObject): Promise<UTSJSONObject> {
const url = `${djDomain}${BOUTIQUE_PATH}router?method=${method}`
const data = buildSignedParams(method, payload)
console.log('rop request', url, data)
return await new Promise((resolve, reject) => {
uni.request({
url,
data,
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
dataType: 'json',
success: (res) => {
console.log('rop response', res.data)
resolve(res.data as UTSJSONObject)
},
fail: (err) => {
console.log('rop error', err)
reject(err)
}
})
})
const url = `${djDomain}${BOUTIQUE_PATH}router?method=${method}`;
const data = buildSignedParams(method, payload);
console.log("rop request", url, data);
return await new Promise((resolve, reject) => {
uni.request({
url,
data,
method: "POST",
header: {
"content-type": "application/x-www-form-urlencoded"
},
dataType: "json",
success: (res) => {
console.log("rop response", res.data);
resolve(res.data as UTSJSONObject);
},
fail: (err) => {
console.log("rop error", err);
reject(err);
}
});
});
}
// 获取短信验证码:dj.api.smartcarlife.sms.get.code
export async function apiGetSmsCode(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = {
...params
}
return await postRop('dj.api.smartcarlife.sms.get.code', data)
const data: UTSJSONObject = {
...params
};
return await postRop("dj.api.smartcarlife.sms.get.code", data);
}
// 手机验证码登录:dj.api.smartcarlife.sms.applogin
export async function apiSmsLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = {
...params
}
// 与旧项目保持一致的固定参数
data['source'] = 'MINIAPP'
data['productCode'] = 'PC00c2'
return await postRop('dj.api.smartcarlife.sms.applogin', data)
const data: UTSJSONObject = {
...params
};
// 与旧项目保持一致的固定参数
data.source = "MINIAPP";
data.productCode = "PC00c2";
return await postRop("dj.api.smartcarlife.sms.applogin", data);
}
// 免登:dj.api.smartcarlife.sms.noSignIn.login
export async function apiAutoLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = {
...params
}
return await postRop('dj.api.smartcarlife.sms.noSignIn.login', data)
const data: UTSJSONObject = {
...params
};
return await postRop("dj.api.smartcarlife.sms.noSignIn.login", data);
}
<template>
<view v-if="isShow" class="publish-popup-mask" @click="closePopup">
<view class="publish-popup-container" @click.stop>
<slot name="content"></slot>
</view>
</view>
<view v-if="isShow"
class="publish-popup-mask"
@click="closePopup">
<view class="publish-popup-container" @click.stop>
<slot name="content"></slot>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue';
import { ref } from "vue";
// Props
const props = defineProps<{
type?: string;
isShowFooter?: boolean;
showTitle?: boolean;
type?: string;
}>();
// 响应式数据
......
<template>
<view class="type-tab">
<scroll-view class="type-box" scroll-x="true" :show-scrollbar="false" scroll-with-animation>
<view class="type-scroll-content">
<view
class="tab-item"
:class="[tabClass(index)]"
v-for="(i, index) in typeList"
:key="index"
@click.stop="tabClick(index, i)"
>
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
</view>
</view>
</view>
</scroll-view>
</view>
<view class="type-tab">
<scroll-view class="type-box"
scroll-with-animation
scroll-x="true"
:show-scrollbar="false">
<view class="type-scroll-content">
<view v-for="(i, index) in typeList"
:key="index"
class="tab-item"
:class="[tabClass(index)]"
@click.stop="tabClick(index, i)">
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script setup lang="uts">
import { ref, computed } from 'vue';
import { get } from '@/utils/common.uts';
import { get } from "@/utils/common.uts";
// Props 类型:使用 any[] 避免响应式对象类型转换问题
const props = withDefaults(defineProps<{
typeList: any[];
tabIndex: number;
nameKey?: string;
isShowCount?: boolean;
nameKey?: string;
tabIndex: number;
typeList: any[];
}>(), {
nameKey: 'tabName',
nameKey: "tabName",
isShowCount: false
});
// Emits
const emit = defineEmits<{
(e: 'tabClick', index: number, item: any): void;
(e: "tabClick", index: number, item: any): void;
}>();
......@@ -44,11 +45,11 @@ const emit = defineEmits<{
// 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包
const getTabName = (item: any): string => {
// 先尝试 get()
let name = get(item, props.nameKey);
const name = get(item, props.nameKey);
if (name != null) {
return name as string;
}
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try {
const jsonStr = JSON.stringify(item);
......@@ -58,55 +59,55 @@ const getTabName = (item: any): string => {
if (name1 != null) {
return name1 as string;
}
const name2 = get(parsed, 'tabName');
const name2 = get(parsed, "tabName");
if (name2 != null) {
return name2 as string;
}
}
} catch (e: any) {
} catch {
// 静默失败
}
return '未知';
return "未知";
};
const getTabCount = (item: any): number => {
// 先尝试 get()
let count = get(item, 'count');
const count = get(item, "count");
if (count != null) {
return count as number;
}
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try {
const jsonStr = JSON.stringify(item);
const parsed = JSON.parse(jsonStr) as any;
if (parsed != null) {
const countValue = get(parsed, 'count');
const countValue = get(parsed, "count");
if (countValue != null) {
return countValue as number;
}
}
} catch (e: any) {
} catch {
// 静默失败
}
return 0;
};
// 方法
const tabClass = (index: number): string => {
let className = '';
let className = "";
if (props.tabIndex == index) {
className = 'active ';
if (index == 0) className += 'first-nav';
else className += 'second-nav';
className = "active ";
if (index == 0) className += "first-nav";
else className += "second-nav";
}
return className;
};
const tabClick = (index: number, item: any) => {
emit('tabClick', index, item);
emit("tabClick", index, item);
};
</script>
......
// composables/useTheme.uts
// 主题 Composable - 提供响应式主题变量和切换接口
import { ref, computed, onMounted } from 'vue'
import { getThemeManager, ThemeName, ThemeVariables } from '@/utils/theme-manager.uts'
import { getScreenSize } from '@/utils/screen-adapt.uts'
import { computed, onMounted, ref } from "vue";
import { getThemeManager, ThemeName, ThemeVariables } from "@/utils/theme-manager.uts";
/**
* 主题 Composable
* 类似 i18n 的使用方式,提供主题变量和切换接口
*/
export function useTheme() {
const themeManager = getThemeManager()
const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName())
const theme = ref<ThemeVariables | null>(themeManager.getCurrentTheme())
const themeManager = getThemeManager();
const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName());
const theme = ref<null | ThemeVariables>(themeManager.getCurrentTheme());
/**
* 设置主题
*/
function setTheme(themeName: ThemeName): boolean {
const success = themeManager.setTheme(themeName)
const success = themeManager.setTheme(themeName);
if (success) {
currentThemeName.value = themeName
theme.value = themeManager.getCurrentTheme()
currentThemeName.value = themeName;
theme.value = themeManager.getCurrentTheme();
}
return success
return success;
}
/**
* 自动选择主题(根据屏幕尺寸)
*/
function autoSelectTheme(): void {
themeManager.autoSelectTheme()
currentThemeName.value = themeManager.getCurrentThemeName()
theme.value = themeManager.getCurrentTheme()
themeManager.autoSelectTheme();
currentThemeName.value = themeManager.getCurrentThemeName();
theme.value = themeManager.getCurrentTheme();
}
/**
......@@ -40,50 +40,50 @@ export function useTheme() {
*/
const spacing = computed(() => {
return (key: string): number => {
return themeManager.getSpacing(key)
}
})
return themeManager.getSpacing(key);
};
});
/**
* 获取圆角值
*/
const borderRadius = computed(() => {
return (key: string): number => {
return themeManager.getBorderRadius(key)
}
})
return themeManager.getBorderRadius(key);
};
});
/**
* 获取字体大小
*/
const fontSize = computed(() => {
return (key: string): number => {
return themeManager.getFontSize(key)
}
})
return themeManager.getFontSize(key);
};
});
/**
* 获取尺寸值
*/
const size = computed(() => {
return (key: string): number => {
return themeManager.getSize(key)
}
})
return themeManager.getSize(key);
};
});
/**
* 获取行高值
*/
const lineHeight = computed(() => {
return (key: string): number => {
return themeManager.getLineHeight(key)
}
})
return themeManager.getLineHeight(key);
};
});
// 初始化时自动选择主题
onMounted(() => {
autoSelectTheme()
})
autoSelectTheme();
});
return {
// 当前主题名称
......@@ -104,5 +104,5 @@ export function useTheme() {
size,
// 获取行高值
lineHeight
}
};
}
// composables/useThemeVariables.uts
// CSS 变量主题 Composable
import { ref, computed, onMounted } from 'vue'
import { getThemeVariablesStyle } from '@/utils/theme-variables.uts'
import { useTheme } from './useTheme.uts'
import { computed, onMounted, ref } from "vue";
import { getThemeVariablesStyle } from "@/utils/theme-variables.uts";
import { useTheme } from "./useTheme.uts";
/**
* CSS 变量主题 Composable
* 提供响应式的 CSS 变量样式对象
*/
export function useThemeVariables() {
const { currentThemeName, autoSelectTheme } = useTheme()
const themeVars = ref<Record<string, string>>({})
const { currentThemeName, autoSelectTheme } = useTheme();
const themeVars = ref<Record<string, string>>({});
/**
* 更新 CSS 变量
*/
function updateThemeVariables(): void {
themeVars.value = getThemeVariablesStyle()
themeVars.value = getThemeVariablesStyle();
}
// 初始化时设置 CSS 变量
onMounted(() => {
updateThemeVariables()
})
updateThemeVariables();
});
// 监听主题变化,自动更新 CSS 变量
const themeVarsComputed = computed(() => {
// 当主题名称变化时,重新计算 CSS 变量
return getThemeVariablesStyle()
})
return getThemeVariablesStyle();
});
return {
// CSS 变量样式对象(用于 :style 绑定)
themeVars: themeVarsComputed,
// 手动更新 CSS 变量
updateThemeVariables
}
};
}
export const proxy = {
dev: {
// 本地地址
target: "http://127.0.0.1:8001",
changeOrigin: true,
rewrite: (path: string) => path.replace("/dev", ""),
},
dev: {
// 本地地址
target: "http://127.0.0.1:8001",
changeOrigin: true,
rewrite: (path: string) => path.replace("/dev", ""),
},
};
export const value = "dev";
/// <reference types="vite/client" />
// / <reference types="vite/client" />
declare module "*.uvue" {
import { DefineComponent } from "vue";
declare module '*.uvue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
declare module '*.vue' {
import { DefineComponent } from 'vue';
declare module "*.vue" {
import { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
......
import { createSSRApp } from "vue";
import { appMixin } from "./utilsApi";
import App from "./App.uvue";
import { appMixin } from "./utilsApi";
export function createApp() {
const app = createSSRApp(App);
......
<template>
<view class="layout">
<view class="bg"></view>
<view class="login flex-col">
<text class="title">登录</text>
<text class="sub-title">手机号码登录</text>
<view class="layout">
<view class="bg"></view>
<view class="login flex-col">
<text class="title">登录</text>
<text class="sub-title">手机号码登录</text>
<view class="input">
<input
type="tel"
v-model="mobile"
placeholder="请输入手机号"
maxlength="11"
auto-blur
/>
<view
v-if="mobile != ''"
class="icon"
@click="clearMobile"
>
<icon
type="clear"
size="16"
color="#000"
></icon>
</view>
</view>
<view class="input">
<input v-model="mobile"
auto-blur
maxlength="11"
placeholder="请输入手机号"
type="tel" />
<view v-if="mobile != ''"
class="icon"
@click="clearMobile">
<icon color="#000"
size="16"
type="clear">
</icon>
</view>
</view>
<view class="input">
<input
type="number"
v-model="code"
placeholder="请输入验证码"
maxlength="4"
auto-blur
/>
<view
v-if="code != ''"
class="icon"
@click="clearCode"
>
<icon
type="clear"
size="16"
color="#000"
></icon>
</view>
<view
:class="['code-btn', count > 0 ? 'code-disabled' : '']"
@click="getSmsCode"
>
{{ count > 0 ? `重新发送(${count}s)` : '获取验证码' }}
</view>
</view>
<button
class="btn"
@click="login"
>
登录
</button>
<view class="form-footer">
<view
class="autoLogin"
@click="toggleReadingStatus"
>
<radio
:checked="readingStatus"
color="#2C66F7"
></radio>
我已阅读并同意
<text @click.stop="openPrivacy">《隐私协议》</text>
</view>
<view class="input">
<input v-model="code"
auto-blur
maxlength="4"
placeholder="请输入验证码"
type="number" />
<view v-if="code != ''"
class="icon"
@click="clearCode">
<icon color="#000"
size="16"
type="clear">
</icon>
</view>
<view class="code-btn"
:class="[count > 0 ? 'code-disabled' : '']"
@click="getSmsCode">
{{ count > 0 ? `重新发送(${count}s)` : '获取验证码' }}
</view>
</view>
<button class="btn"
@click="login">
登录
</button>
<view class="form-footer">
<view class="autoLogin"
@click="toggleReadingStatus">
<radio :checked="readingStatus"
color="#2C66F7">
</radio>
我已阅读并同意
<text @click.stop="openPrivacy">《隐私协议》</text>
</view>
<view
class="autoLogin"
@click="toggleNoSignIn"
>
<radio
:checked="noSignIn"
color="#2C66F7"
></radio>
30天内免登录
</view>
<view class="autoLogin"
@click="toggleNoSignIn">
<radio :checked="noSignIn"
color="#2C66F7">
</radio>
30天内免登录
</view>
</view>
</view>
<view class="app-code flex">
APP编码:{{ deviceId }}
<view class="sprite-icon icon-clone"
@click="copyDeviceId">
</view>
</view>
</view>
<view class="app-code flex">
APP编码:{{ deviceId }}
<view
class="sprite-icon icon-clone"
@click="copyDeviceId"
></view>
</view>
</view>
</template>
</template>
<script setup lang="uts">
import { ref, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { apiSmsLogin, apiGetSmsCode, apiAutoLogin } from '@/api/user-api.uts'
import { storage } from '@/utils/storage.uts'
<script setup lang="uts">
import { ref, watch } from "vue";
import { apiAutoLogin, apiGetSmsCode, apiSmsLogin } from "@/api/user-api.uts";
import { storage } from "@/utils/storage.uts";
import { onLoad } from "@dcloudio/uni-app";
// 手机号正则
const phoneRex = /^[1]([3-9])[0-9]{9}$/
const phoneRex = /^1([3-9])\d{9}$/;
// 登录返回 data 的结构(这里只挑我们需要的字段)
type LoginResultData = {
loginUserInfoList: any[] | null
noSignInUuid: string | null
sessionId: string | null
noSignInUuid: null | string
sessionId: null | string
}
const mobile = ref<string>('')
const code = ref<string>('')
const count = ref<number>(0)
const noSignIn = ref<boolean>(true)
const readingStatus = ref<boolean>(false)
const deviceId = ref<string>('')
// 简单登录节流,防止连续点击
let lastLoginAt = 0
const LOGIN_INTERVAL_MS = 200
// 先定义会被其他函数调用的函数:getAccountLoginList / jump / doLogin / login / countDown
const getAccountLoginList = (loginUserInfoList: any[]): void => {
const stepIndex = loginUserInfoList.length == 1 ? 1 : 0
uni.navigateTo({
url: `/pages/common/accountItems?stepIndex=${stepIndex}`
})
}
const jump = (data: any, remember: boolean): void => {
const loginData = data as LoginResultData
const loginUserInfoList = loginData.loginUserInfoList
const sessionIdVal = loginData.sessionId
const noSignInUuidVal = loginData.noSignInUuid
if (loginUserInfoList != null && loginUserInfoList.length > 0) {
if (sessionIdVal != null && sessionIdVal != '') {
storage.set('sessionId', sessionIdVal, 0)
}
if (noSignInUuidVal != null && noSignInUuidVal != '' && remember) {
storage.set('noSignInUuid', noSignInUuidVal, 0)
}
getAccountLoginList(loginUserInfoList)
} else {
uni.reLaunch({
url: '/pages/common/nothing'
})
}
}
const doLogin = async (): Promise<void> => {
console.log('doLogin',mobile)
const m = mobile.value
const smsCode = code.value
const remember = noSignIn.value
const agreed = readingStatus.value
try {
if (m == '') {
throw new Error('请输入手机号')
}
if (!phoneRex.test(m)) {
throw new Error('请输入正确的手机号')
}
if (smsCode == '') {
throw new Error('请输入验证码')
}
if (!agreed) {
throw new Error('请您阅读并同意《隐私协议》')
}
const params: UTSJSONObject = {
mobile: m,
code: smsCode
}
if (remember) {
params['noSignIn'] = remember
}
uni.showLoading({
title: '加载中',
mask: true
})
console.log('res9032903920')
const res = await apiSmsLogin(params)
console.log('res',res)
uni.hideLoading()
const resCode = res != null ? (res.code as number | null) : null
const data = res != null ? (res.data as any | null) : null
const message = res != null ? (res.message as string | null) : null
if (resCode == 0 && data != null) {
jump(data, remember)
} else {
uni.showModal({
title: '温馨提示',
content: message ?? '登录失败',
showCancel: false,
confirmText: '知道了',
confirmColor: '#347BFF'
})
console.log(`${m}登录失败,失败原因:${message}`)
}
} catch (err) {
const msg = `${err}`
uni.hideLoading()
uni.showToast({
title: msg,
icon: 'none'
})
}
}
const login = (): void => {
const now = Date.now()
if (now - lastLoginAt < LOGIN_INTERVAL_MS) {
return
}
lastLoginAt = now
doLogin()
}
function countDown(initial: number): void {
if (initial > 0) {
count.value = initial
}
setTimeout(() => {
const current = count.value
const next = current - 1
count.value = next
if (next > 0) {
countDown(next)
} else {
count.value = 0
}
}, 1000)
}
// 下面是其余业务函数
const autoLoginByMobile = (): void => {
const m = mobile.value
const c = code.value
if (c != '' && m != '' && c.length == 4 && phoneRex.test(m)) {
login()
}
}
const clearMobile = (): void => {
mobile.value = ''
}
const clearCode = (): void => {
code.value = ''
}
const copyDeviceId = (): void => {
uni.setClipboardData({
data: deviceId.value,
success() {
uni.showToast({
title: '复制成功',
icon: 'success'
})
}
})
}
const autoLogin = async (noSignInUuid: string): Promise<void> => {
if (noSignInUuid == '') return
uni.showLoading({
title: '加载中',
mask: true
})
try {
const res = await apiAutoLogin({
noSignInUuid
} as UTSJSONObject)
uni.hideLoading()
const data = res != null ? (res.data as any | null) : null
if (data != null) {
jump(data, true)
}
} catch (error) {
uni.hideLoading()
}
}
const getSmsCode = async (): Promise<void> => {
const m = mobile.value
const c = count.value
try {
if (m == '') {
throw new Error('请输入手机号')
}
if (!phoneRex.test(m)) {
throw new Error('请输入正确的手机号')
}
if (c > 0) {
throw new Error('验证码发送过于频繁,请稍后再试')
}
uni.showLoading({
title: '加载中',
mask: true
})
const res = await apiGetSmsCode({
mobile: m
} as UTSJSONObject)
uni.hideLoading()
const codeVal = res != null ? (res.code as string | null) : null
const message = res != null ? (res.message as string | null) : null
if (codeVal == '0') {
uni.showToast({
title: '验证码已发送',
icon: 'none'
})
countDown(60)
} else {
throw new Error(message ?? '发送验证码失败')
}
} catch (err) {
const msg = `${err}`
uni.hideLoading()
uni.showToast({
title: msg,
icon: 'none'
})
}
}
const openPrivacy = (): void => {
const url = 'https://img01.glsx.com.cn/weapp/resource/saas/app/privacy.html'
uni.navigateTo({
url: `/pages/common/webview?url=${url}`
})
}
onLoad((options: UTSJSONObject | null) => {
const optMobile = options != null ? (options['mobile'] as string | null) : null
if (optMobile != null && optMobile != '') {
mobile.value = optMobile
}
const noSignInUuid = storage.get('noSignInUuid') as string | null
if (noSignInUuid != null && noSignInUuid != '') {
autoLogin(noSignInUuid)
}
const info = uni.getDeviceInfo()
if (info != null && info.deviceId != null) {
deviceId.value = info.deviceId
}
})
watch(mobile, () => {
autoLoginByMobile()
})
watch(code, () => {
autoLoginByMobile()
})
const mobile = ref<string>("");
const code = ref<string>("");
const count = ref<number>(0);
const noSignIn = ref<boolean>(true);
const readingStatus = ref<boolean>(false);
const deviceId = ref<string>("");
// 简单登录节流,防止连续点击
let lastLoginAt = 0;
const LOGIN_INTERVAL_MS = 200;
// 先定义会被其他函数调用的函数:getAccountLoginList / jump / doLogin / login / countDown
const getAccountLoginList = (loginUserInfoList: any[]): void => {
const stepIndex = loginUserInfoList.length == 1 ? 1 : 0;
uni.navigateTo({
url: `/pages/common/accountItems?stepIndex=${stepIndex}`
});
};
const jump = (data: any, remember: boolean): void => {
const loginData = data as LoginResultData;
const loginUserInfoList = loginData.loginUserInfoList;
const sessionIdVal = loginData.sessionId;
const noSignInUuidVal = loginData.noSignInUuid;
if (loginUserInfoList != null && loginUserInfoList.length > 0) {
if (sessionIdVal != null && sessionIdVal != "") {
storage.set("sessionId", sessionIdVal, 0);
}
if (noSignInUuidVal != null && noSignInUuidVal != "" && remember) {
storage.set("noSignInUuid", noSignInUuidVal, 0);
}
getAccountLoginList(loginUserInfoList);
} else {
uni.reLaunch({
url: "/pages/common/nothing"
});
}
};
const doLogin = async (): Promise<void> => {
console.log("doLogin", mobile);
const m = mobile.value;
const smsCode = code.value;
const remember = noSignIn.value;
const agreed = readingStatus.value;
try {
if (m == "") {
throw new Error("请输入手机号");
}
if (!phoneRex.test(m)) {
throw new Error("请输入正确的手机号");
}
if (smsCode == "") {
throw new Error("请输入验证码");
}
if (!agreed) {
throw new Error("请您阅读并同意《隐私协议》");
}
const params: UTSJSONObject = {
mobile: m,
code: smsCode
};
if (remember) {
params.noSignIn = remember;
}
uni.showLoading({
title: "加载中",
mask: true
});
console.log("res9032903920");
const res = await apiSmsLogin(params);
console.log("res", res);
uni.hideLoading();
const resCode = res != null ? (res.code as null | number) : null;
const data = res != null ? (res.data as any | null) : null;
const message = res != null ? (res.message as null | string) : null;
if (resCode == 0 && data != null) {
jump(data, remember);
} else {
uni.showModal({
title: "温馨提示",
content: message ?? "登录失败",
showCancel: false,
confirmText: "知道了",
confirmColor: "#347BFF"
});
console.log(`${m}登录失败,失败原因:${message}`);
}
} catch (error) {
const msg = `${error}`;
uni.hideLoading();
uni.showToast({
title: msg,
icon: "none"
});
}
};
const login = (): void => {
const now = Date.now();
if (now - lastLoginAt < LOGIN_INTERVAL_MS) {
return;
}
lastLoginAt = now;
doLogin();
};
function countDown(initial: number): void {
if (initial > 0) {
count.value = initial;
}
setTimeout(() => {
const current = count.value;
const next = current - 1;
count.value = next;
if (next > 0) {
countDown(next);
} else {
count.value = 0;
}
}, 1000);
}
// 下面是其余业务函数
const autoLoginByMobile = (): void => {
const m = mobile.value;
const c = code.value;
if (c != "" && m != "" && c.length == 4 && phoneRex.test(m)) {
login();
}
};
const clearMobile = (): void => {
mobile.value = "";
};
const clearCode = (): void => {
code.value = "";
};
const copyDeviceId = (): void => {
uni.setClipboardData({
data: deviceId.value,
success() {
uni.showToast({
title: "复制成功",
icon: "success"
});
}
});
};
const autoLogin = async (noSignInUuid: string): Promise<void> => {
if (noSignInUuid == "") return;
uni.showLoading({
title: "加载中",
mask: true
});
try {
const res = await apiAutoLogin({
noSignInUuid
} as UTSJSONObject);
uni.hideLoading();
const data = res != null ? (res.data as any | null) : null;
if (data != null) {
jump(data, true);
}
} catch {
uni.hideLoading();
}
};
const getSmsCode = async (): Promise<void> => {
const m = mobile.value;
const c = count.value;
try {
if (m == "") {
throw new Error("请输入手机号");
}
if (!phoneRex.test(m)) {
throw new Error("请输入正确的手机号");
}
if (c > 0) {
throw new Error("验证码发送过于频繁,请稍后再试");
}
uni.showLoading({
title: "加载中",
mask: true
});
const res = await apiGetSmsCode({
mobile: m
} as UTSJSONObject);
uni.hideLoading();
const codeVal = res != null ? (res.code as null | string) : null;
const message = res != null ? (res.message as null | string) : null;
if (codeVal == "0") {
uni.showToast({
title: "验证码已发送",
icon: "none"
});
countDown(60);
} else {
throw new Error(message ?? "发送验证码失败");
}
} catch (error) {
const msg = `${error}`;
uni.hideLoading();
uni.showToast({
title: msg,
icon: "none"
});
}
};
const openPrivacy = (): void => {
const url = "https://img01.glsx.com.cn/weapp/resource/saas/app/privacy.html";
uni.navigateTo({
url: `/pages/common/webview?url=${url}`
});
};
onLoad((options: null | UTSJSONObject) => {
const optMobile = options != null ? (options.mobile as null | string) : null;
if (optMobile != null && optMobile != "") {
mobile.value = optMobile;
}
const noSignInUuid = storage.get("noSignInUuid") as null | string;
if (noSignInUuid != null && noSignInUuid != "") {
autoLogin(noSignInUuid);
}
const info = uni.getDeviceInfo();
if (info != null && info.deviceId != null) {
deviceId.value = info.deviceId;
}
});
watch(mobile, () => {
autoLoginByMobile();
});
watch(code, () => {
autoLoginByMobile();
});
function toggleReadingStatus(): void {
readingStatus.value = !readingStatus.value
}
readingStatus.value = !readingStatus.value;
}
function toggleNoSignIn(): void {
noSignIn.value = !noSignIn.value
}
</script>
function toggleNoSignIn(): void {
noSignIn.value = !noSignIn.value;
}
</script>
<style scoped lang="scss">
.layout {
......
<template>
<view
style="flex: 1"
>
<view class="chart-container" id="chart-container-1">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart
ref="chartRef"
@finished="initChart"
class="chart"
:enable-hover="false"
:is-clickable="false"
:before-delay="0">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="chartRef" @finished="initChart" class="chart"></l-echart>
<!-- #endif -->
</view>
<view class="chart-container" id="chart-container-2" style="margin-top: 16px">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart
ref="lineChartRef"
@finished="initLineChart"
class="chart"
:enable-hover="false"
:is-clickable="false"
:before-delay="0">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="lineChartRef" @finished="initLineChart" class="chart"></l-echart>
<!-- #endif -->
</view>
</view>
<view style="flex: 1">
<view id="chart-container-1" class="chart-container">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="chartRef"
:before-delay="0"
class="chart"
:enable-hover="false"
:is-clickable="false"
@finished="initChart">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="chartRef"
class="chart"
@finished="initChart">
</l-echart>
<!-- #endif -->
</view>
<view id="chart-container-2"
class="chart-container"
style="margin-top: 16px">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="lineChartRef"
:before-delay="0"
class="chart"
:enable-hover="false"
:is-clickable="false"
@finished="initLineChart">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="lineChartRef"
class="chart"
@finished="initLineChart">
</l-echart>
<!-- #endif -->
</view>
</view>
</template>
<script setup lang="uts">
import { get } from "@/utils/common.uts";
......
<template>
<!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 -->
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
<!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 -->
<!-- 顶部标题区域(渐变改为纯色,兼容 App) -->
<view class="bg-blue-500 px-6 py-8 flex-col">
<text class="text-3xl font-bold text-white mb-2 block">gl_tape 迁移示例</text>
<text class="text-base text-white opacity-90 block">plus.* API → uni-app x + UTS</text>
</view>
<!-- 内容区:使用默认方向,由 manifest.json 的 flex-direction 控制 -->
<view class="px-5 py-5 flex-col">
<!-- plus.runtime 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.runtime 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.runtime.version</text>
<text class="text-sm text-gray-600 block">新代码:getAppVersion()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion">获取版本号</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">打开URL</button>
</view>
<view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ runtimeResult }}</text>
</view>
</view>
<!-- plus.screen 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.screen 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.screen.lockOrientation()</text>
<text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait">锁定竖屏</button>
<button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">锁定横屏</button>
<button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">保持常亮</button>
</view>
<view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ screenResult }}</text>
</view>
</view>
<!-- plus.io 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.io 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.io.requestFileSystem()</text>
<text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text>
</view>
<view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath">获取文件路径</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">写入文件</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">读取文件</button>
</view>
<view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800 break-words">{{ ioResult }}</text>
</view>
</view>
<!-- plus.os 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.os 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.os.name == "iOS"</text>
<text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS">检测系统</button>
</view>
<view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ osResult }}</text>
</view>
</view>
<!-- plus.navigator 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.navigator 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.navigator.getStatusbarHeight()</text>
<text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight">获取状态栏高度</button>
</view>
<view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ navigatorResult }}</text>
</view>
</view>
<!-- plus.android/plus.ios 说明 -->
<view class="bg-yellow-100 border border-yellow-400 rounded-lg p-4 mb-4 flex-col">
<text class="text-lg font-semibold text-yellow-500 mb-2 block">⚠️ plus.android / plus.ios 迁移说明</text>
<text class="text-gray-700 text-sm leading-relaxed block mb-2">
uni-app x 中不再支持 JS 反射调用原生 API(plus.android.importClass 等)。
</text>
<text class="text-gray-700 text-sm leading-relaxed block mb-2">
需要创建 UTS 插件,在 UTS 代码中直接调用 Android/iOS 原生 API。
</text>
<text class="text-gray-700 text-sm leading-relaxed block">
示例:创建 utssdk/app-android/index.uts,在其中使用 Kotlin 语法调用 Android SDK。
</text>
</view>
<!-- 迁移对比说明 -->
<view class="bg-blue-50 border border-blue-300 rounded-lg p-4 mb-4 flex-col">
<text class="text-lg font-semibold text-blue-700 mb-2 block">📝 迁移要点</text>
<view class="flex-col">
<text class="text-blue-700 text-sm leading-relaxed block">1. plus.runtime → uni API + UTS 工具函数</text>
<text class="text-blue-700 text-sm leading-relaxed block">2. plus.screen → manifest.json 配置 + uni.setKeepScreenOn</text>
<text class="text-blue-700 text-sm leading-relaxed block">3. plus.io → uni.getFileSystemManager</text>
<text class="text-blue-700 text-sm leading-relaxed block">4. plus.android/ios → UTS 插件(直接调用原生 API)</text>
<text class="text-blue-700 text-sm leading-relaxed block">5. plus.os → 条件编译 + UTS 工具函数</text>
</view>
</view>
</view>
</scroll-view>
<!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 -->
<scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 -->
<!-- 顶部标题区域(渐变改为纯色,兼容 App) -->
<view class="bg-blue-500 px-6 py-8 flex-col">
<text class="text-3xl font-bold text-white mb-2 block">gl_tape 迁移示例</text>
<text class="text-base text-white opacity-90 block">plus.* API → uni-app x + UTS</text>
</view>
<!-- 内容区:使用默认方向,由 manifest.json 的 flex-direction 控制 -->
<view class="px-5 py-5 flex-col">
<!-- plus.runtime 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.runtime 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.runtime.version</text>
<text class="text-sm text-gray-600 block">新代码:getAppVersion()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion">
获取版本号
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">
打开URL
</button>
</view>
<view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ runtimeResult }}</text>
</view>
</view>
<!-- plus.screen 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.screen 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.screen.lockOrientation()</text>
<text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait">
锁定竖屏
</button>
<button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">
锁定横屏
</button>
<button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">
保持常亮
</button>
</view>
<view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ screenResult }}</text>
</view>
</view>
<!-- plus.io 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.io 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.io.requestFileSystem()</text>
<text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text>
</view>
<view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath">
获取文件路径
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">
写入文件
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">
读取文件
</button>
</view>
<view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800 break-words">{{ ioResult }}</text>
</view>
</view>
<!-- plus.os 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.os 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.os.name == "iOS"</text>
<text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS">
检测系统
</button>
</view>
<view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ osResult }}</text>
</view>
</view>
<!-- plus.navigator 示例 -->
<view class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">plus.navigator 迁移</text>
<view class="mb-3 flex-col">
<text class="text-sm text-gray-600 block">原代码:plus.navigator.getStatusbarHeight()</text>
<text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text>
</view>
<view class="flex flex-row flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight">
获取状态栏高度
</button>
</view>
<view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ navigatorResult }}</text>
</view>
</view>
<!-- plus.android/plus.ios 说明 -->
<view class="bg-yellow-100 border border-yellow-400 rounded-lg p-4 mb-4 flex-col">
<text class="text-lg font-semibold text-yellow-500 mb-2 block">⚠️ plus.android / plus.ios 迁移说明</text>
<text class="text-gray-700 text-sm leading-relaxed block mb-2">
uni-app x 中不再支持 JS 反射调用原生 API(plus.android.importClass 等)。
</text>
<text class="text-gray-700 text-sm leading-relaxed block mb-2">
需要创建 UTS 插件,在 UTS 代码中直接调用 Android/iOS 原生 API。
</text>
<text class="text-gray-700 text-sm leading-relaxed block">
示例:创建 utssdk/app-android/index.uts,在其中使用 Kotlin 语法调用 Android SDK。
</text>
</view>
<!-- 迁移对比说明 -->
<view class="bg-blue-50 border border-blue-300 rounded-lg p-4 mb-4 flex-col">
<text class="text-lg font-semibold text-blue-700 mb-2 block">📝 迁移要点</text>
<view class="flex-col">
<text class="text-blue-700 text-sm leading-relaxed block">1. plus.runtime → uni API + UTS 工具函数</text>
<text class="text-blue-700 text-sm leading-relaxed block">2. plus.screen → manifest.json 配置 + uni.setKeepScreenOn</text>
<text class="text-blue-700 text-sm leading-relaxed block">3. plus.io → uni.getFileSystemManager</text>
<text class="text-blue-700 text-sm leading-relaxed block">4. plus.android/ios → UTS 插件(直接调用原生 API)</text>
<text class="text-blue-700 text-sm leading-relaxed block">5. plus.os → 条件编译 + UTS 工具函数</text>
</view>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
import { getAppVersion, openURL, getAppInfo } from "@/utils/plus-runtime"
import { lockOrientation, unlockOrientation, setKeepScreenOn } from "@/utils/plus-screen"
import { getFilePath, writeFile, readFile } from "@/utils/plus-io"
import { isIOS, isAndroid, getOSName } from "@/utils/plus-os"
import { getStatusbarHeight } from "@/utils/plus-navigator"
const runtimeResult = ref<string>("")
const screenResult = ref<string>("")
const ioResult = ref<string>("")
const osResult = ref<string>("")
const navigatorResult = ref<string>("")
import { getFilePath, readFile, writeFile } from "@/utils/plus-io";
import { getStatusbarHeight } from "@/utils/plus-navigator";
import { getOSName, isAndroid, isIOS } from "@/utils/plus-os";
import { getAppInfo, getAppVersion, openURL } from "@/utils/plus-runtime";
import { lockOrientation, setKeepScreenOn } from "@/utils/plus-screen";
const runtimeResult = ref<string>("");
const screenResult = ref<string>("");
const ioResult = ref<string>("");
const osResult = ref<string>("");
const navigatorResult = ref<string>("");
// plus.runtime 示例
const handleGetVersion = () => {
const version = getAppVersion()
const appInfo = getAppInfo()
runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}`
}
const version = getAppVersion();
const appInfo = getAppInfo();
runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}`;
};
const handleOpenURL = () => {
openURL("https://uniapp.dcloud.net.cn/")
runtimeResult.value = "已尝试打开 uni-app 官网"
}
openURL("https://uniapp.dcloud.net.cn/");
runtimeResult.value = "已尝试打开 uni-app 官网";
};
// plus.screen 示例
const handleLockPortrait = () => {
lockOrientation("portrait-primary")
screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)"
}
lockOrientation("portrait-primary");
screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)";
};
const handleLockLandscape = () => {
lockOrientation("landscape-primary")
screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)"
}
lockOrientation("landscape-primary");
screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)";
};
const handleKeepScreenOn = () => {
setKeepScreenOn(true)
screenResult.value = "已设置屏幕常亮"
}
setKeepScreenOn(true);
screenResult.value = "已设置屏幕常亮";
};
// plus.io 示例
const handleGetFilePath = async () => {
......@@ -173,12 +195,12 @@ const handleGetFilePath = async () => {
// #ifndef APP
path = await getFilePath();
// #endif
ioResult.value = `文件路径: ${path}`
ioResult.value = `文件路径: ${path}`;
} catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}`
ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}`;
}
}
};
const handleWriteFile = async () => {
try {
......@@ -189,14 +211,14 @@ const handleWriteFile = async () => {
// #ifndef APP
testPath = `${await getFilePath()}/hello.txt`;
// #endif
await writeFile(testPath, "Hello uni-app x!")
ioResult.value = `文件写入成功: ${testPath}`
await writeFile(testPath, "Hello uni-app x!");
ioResult.value = `文件写入成功: ${testPath}`;
} catch (error: any) {
console.error("writeFile fail: ", error);
console.error("writeFile fail:", error);
// UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}`
ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}`;
}
}
};
const handleReadFile = async () => {
try {
......@@ -207,27 +229,27 @@ const handleReadFile = async () => {
// #ifndef APP
testPath = `${await getFilePath()}/hello.txt`;
// #endif
const content = await readFile(testPath)
ioResult.value = `文件内容: ${content}`
const content = await readFile(testPath);
ioResult.value = `文件内容: ${content}`;
} catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}`
ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}`;
}
}
};
// plus.os 示例
const handleCheckOS = () => {
const osName = getOSName()
const isIOSDevice = isIOS()
const isAndroidDevice = isAndroid()
osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}`
}
const osName = getOSName();
const isIOSDevice = isIOS();
const isAndroidDevice = isAndroid();
osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}`;
};
// plus.navigator 示例
const handleGetStatusbarHeight = () => {
const height = getStatusbarHeight()
navigatorResult.value = `状态栏高度: ${height}px`
}
const height = getStatusbarHeight();
navigatorResult.value = `状态栏高度: ${height}px`;
};
</script>
<style>
......
<template>
<scroll-view class="flex flex-col p-5 bg-gray-100" style="flex: 1" scroll-y="true">
<view class="flex flex-col mb-5 p-5 bg-white rounded-lg shadow-sm flex-shrink-0">
<text class="text-2xl font-bold text-gray-800 mb-2">SqliteStore 示例</text>
<text class="text-sm text-gray-600">基于 SQLite 的本地存储方案(解决并发同步问题)</text>
</view>
<!-- 主内容区域:左右布局 -->
<view class="flex flex-row gap-5 flex-1 overflow-hidden min-h-0">
<!-- 左侧:操作按钮区域 -->
<view class="flex flex-col bg-white rounded-lg p-4 shadow-sm overflow-y-auto overflow-x-hidden min-h-0" style="flex: 0 0 320px">
<view class="flex flex-col gap-4">
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 relative pb-2 border-b-2 border-gray-200">基础操作</text>
<view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleInsert">插入数据</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleInsertWithId">指定ID插入</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQuery">查询数据</button>
<button class="btn btn-warning mr-2 mb-2" @click="handleUpdate">更新数据</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleDeleteSelected">删除选中</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
查询操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAdults">查询成年人</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryActive">查询活跃用户</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryByEmail">按邮箱查询</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAll">查询全部</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
批量操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleBatchInsert">批量插入</button>
<button class="btn btn-success mr-2 mb-2" @click="handleBatchUpdate">批量更新</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleBatchDelete">批量删除</button>
</view>
<view class="flex flex-wrap mt-2">
<button
class="btn btn-success mr-2 mb-2"
:disabled="isInserting"
@click="handleLargeBatchInsert"
>
{{ isInserting ? '插入中...' : '大数据批量插入' }}
</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
工具操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-dark mr-2 mb-2" @click="handleGetStats">统计信息</button>
<button class="btn btn-dark mr-2 mb-2" @click="handleClear">清空数据</button>
</view>
</view>
</view>
</view>
<!-- 右侧:数据展示区域(整体滚动由外层 scroll-view 控制,这里不再嵌套 scroll-view) -->
<view class="flex-1 flex flex-col gap-5 overflow-hidden min-h-0 relative">
<!-- Loading 遮罩 -->
<view v-if="isInserting" class="absolute inset-0 bg-gradient-to-br from-indigo-500/90 to-purple-500/90 backdrop-blur-sm flex justify-center items-center z-[1000] rounded-lg">
<view class="flex flex-col items-center justify-center p-8 bg-white rounded-2xl shadow-xl min-w-[200px]">
<view class="w-12 h-12 border-4 border-gray-200 border-t-indigo-500 rounded-full animate-spin mb-4"></view>
<text class="text-base text-gray-800 font-bold block mb-2">正在插入数据,请稍候...</text>
<text class="text-xs text-gray-600">请勿重复点击</text>
</view>
</view>
<scroll-view class="flex flex-col p-5 bg-gray-100"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col mb-5 p-5 bg-white rounded-lg shadow-sm flex-shrink-0">
<text class="text-2xl font-bold text-gray-800 mb-2">SqliteStore 示例</text>
<text class="text-sm text-gray-600">基于 SQLite 的本地存储方案(解决并发同步问题)</text>
</view>
<!-- 主内容区域:左右布局 -->
<view class="flex flex-row gap-5 flex-1 overflow-hidden min-h-0">
<!-- 左侧:操作按钮区域 -->
<view class="flex flex-col bg-white rounded-lg p-4 shadow-sm overflow-y-auto overflow-x-hidden min-h-0" style="flex: 0 0 320px">
<view class="flex flex-col gap-4">
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 relative pb-2 border-b-2 border-gray-200">基础操作</text>
<view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleInsert">
插入数据
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleInsertWithId">
指定ID插入
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQuery">
查询数据
</button>
<button class="btn btn-warning mr-2 mb-2" @click="handleUpdate">
更新数据
</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleDeleteSelected">
删除选中
</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
查询操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAdults">
查询成年人
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryActive">
查询活跃用户
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryByEmail">
按邮箱查询
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAll">
查询全部
</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
批量操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleBatchInsert">
批量插入
</button>
<button class="btn btn-success mr-2 mb-2" @click="handleBatchUpdate">
批量更新
</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleBatchDelete">
批量删除
</button>
</view>
<view class="flex flex-wrap mt-2">
<button class="btn btn-success mr-2 mb-2"
:disabled="isInserting"
@click="handleLargeBatchInsert">
{{ isInserting ? '插入中...' : '大数据批量插入' }}
</button>
</view>
</view>
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 block relative pb-2 border-b-2 border-gray-200">
<text class="absolute bottom-[-2px] left-0 w-10 h-0.5 bg-gradient-to-r from-indigo-500 to-purple-500 rounded"></text>
工具操作
</text>
<view class="flex flex-wrap">
<button class="btn btn-dark mr-2 mb-2" @click="handleGetStats">
统计信息
</button>
<button class="btn btn-dark mr-2 mb-2" @click="handleClear">
清空数据
</button>
</view>
</view>
</view>
</view>
<!-- 右侧:数据展示区域(整体滚动由外层 scroll-view 控制,这里不再嵌套 scroll-view) -->
<view class="flex-1 flex flex-col gap-5 overflow-hidden min-h-0 relative">
<!-- Loading 遮罩 -->
<view v-if="isInserting" class="absolute inset-0 bg-gradient-to-br from-indigo-500/90 to-purple-500/90 backdrop-blur-sm flex justify-center items-center z-[1000] rounded-lg">
<view class="flex flex-col items-center justify-center p-8 bg-white rounded-2xl shadow-xl min-w-[200px]">
<view class="w-12 h-12 border-4 border-gray-200 border-t-indigo-500 rounded-full animate-spin mb-4"></view>
<text class="text-base text-gray-800 font-bold block mb-2">正在插入数据,请稍候...</text>
<text class="text-xs text-gray-600">请勿重复点击</text>
</view>
</view>
<!-- 数据列表:右侧区域上半部分,高度约 50%,内部可滚动 -->
<view
class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5"
>
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
数据列表
</text>
<view class="flex flex-col items-end gap-1">
<text class="text-sm text-indigo-500 font-semibold px-3 py-1 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl">共 {{ dataList.length }} 条</text>
</view>
</view>
<!-- 数据列表内容 -->
<view class="flex-1 overflow-hidden min-h-0">
<view v-if="isLoading" class="flex justify-center items-center p-10">
<view class="flex flex-col items-center gap-3">
<view class="w-8 h-8 border-4 border-gray-200 border-t-indigo-500 rounded-full animate-spin"></view>
<text class="text-sm text-gray-500">加载中...</text>
</view>
</view>
<view v-else-if="dataList.length == 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无数据,点击左侧按钮进行操作</text>
</view>
<view v-else class="flex flex-col border border-gray-200 rounded overflow-hidden bg-white shadow-sm">
<!-- 表头 -->
<view class="flex flex-row bg-gray-100 border-b-2 border-gray-300">
<view class="table-col-checkbox" @click.stop="toggleSelectAll">
<checkbox
value="select-all"
:checked="isAllSelected()"
@click.stop="toggleSelectAll"
/>
</view>
<view class="table-col-id">
<text class="text-sm text-gray-700 font-bold">ID</text>
</view>
<view class="table-col-name">
<text class="text-sm text-gray-700 font-bold">姓名</text>
</view>
<view class="table-col-age">
<text class="text-sm text-gray-700 font-bold">年龄</text>
</view>
<view class="table-col-email">
<text class="text-sm text-gray-700 font-bold">邮箱</text>
</view>
<view class="table-col-status">
<text class="text-sm text-gray-700 font-bold">状态</text>
</view>
<view class="table-col-time">
<text class="text-sm text-gray-700 font-bold">创建时间</text>
</view>
</view>
<!-- 表格内容 -->
<view v-for="(item, index) in dataList" :key="item.id" class="flex flex-row border-b border-gray-200 bg-white" :class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-col-checkbox" @click.stop="toggleSelect(item.id)">
<checkbox
:value="item.id"
:checked="isSelected(item.id)"
@click.stop="toggleSelect(item.id)"
/>
</view>
<view class="table-col-id">
<text class="text-sm text-gray-800">{{ item.id }}</text>
</view>
<view class="table-col-name">
<text class="text-sm text-gray-800">{{ item.name }}</text>
</view>
<view class="table-col-age">
<text class="text-sm text-gray-800">{{ item.age }}</text>
</view>
<view class="table-col-email">
<text class="text-sm text-gray-800">{{ item.email }}</text>
</view>
<view class="table-col-status">
<text
class="px-2 py-1 rounded text-xs"
:class="item.status == 'active' ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'"
>
{{ item.status == "active" ? "活跃" : "非活跃" }}
</text>
</view>
<view class="table-col-time">
<text class="text-sm text-gray-800">{{ formatTime(item.created_at) }}</text>
</view>
</view>
</view>
</view>
</view>
<!-- 日志区域:右侧区域下半部分,高度约 50%,内部可滚动 -->
<view
class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5"
>
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
操作日志
</text>
<button class="btn btn-danger text-xs" @click="clearLogs">清空日志</button>
</view>
<!-- 日志内容 -->
<view class="flex-1 overflow-hidden min-h-0">
<view v-if="logs.length == 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无日志</text>
</view>
<view v-else class="flex flex-col border border-gray-200 rounded overflow-hidden bg-white shadow-sm">
<!-- 表头 -->
<view class="flex flex-row bg-gray-100 border-b-2 border-gray-300">
<view class="table-log-time">
<text class="text-xs text-gray-700 font-bold">时间</text>
</view>
<view class="table-log-message">
<text class="text-xs text-gray-700 font-bold">操作内容</text>
</view>
</view>
<!-- 表格内容 -->
<view v-for="(log, index) in logs" :key="index" class="flex flex-row border-b border-gray-200 bg-white" :class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-log-time">
<text class="text-xs text-indigo-500 font-medium">{{ log.time }}</text>
</view>
<view class="table-log-message">
<text class="text-xs text-gray-800">{{ log.message }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
<!-- 数据列表:右侧区域上半部分,高度约 50%,内部可滚动 -->
<view class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5">
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
数据列表
</text>
<view class="flex flex-col items-end gap-1">
<text class="text-sm text-indigo-500 font-semibold px-3 py-1 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl">共 {{ dataList.length }} 条</text>
</view>
</view>
<!-- 数据列表内容 -->
<view class="flex-1 overflow-hidden min-h-0">
<view v-if="isLoading" class="flex justify-center items-center p-10">
<view class="flex flex-col items-center gap-3">
<view class="w-8 h-8 border-4 border-gray-200 border-t-indigo-500 rounded-full animate-spin"></view>
<text class="text-sm text-gray-500">加载中...</text>
</view>
</view>
<view v-else-if="dataList.length === 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无数据,点击左侧按钮进行操作</text>
</view>
<view v-else class="flex flex-col border border-gray-200 rounded overflow-hidden bg-white shadow-sm">
<!-- 表头 -->
<view class="flex flex-row bg-gray-100 border-b-2 border-gray-300">
<view class="table-col-checkbox" @click.stop="toggleSelectAll">
<checkbox :checked="isAllSelected()"
value="select-all"
@click.stop="toggleSelectAll" />
</view>
<view class="table-col-id">
<text class="text-sm text-gray-700 font-bold">ID</text>
</view>
<view class="table-col-name">
<text class="text-sm text-gray-700 font-bold">姓名</text>
</view>
<view class="table-col-age">
<text class="text-sm text-gray-700 font-bold">年龄</text>
</view>
<view class="table-col-email">
<text class="text-sm text-gray-700 font-bold">邮箱</text>
</view>
<view class="table-col-status">
<text class="text-sm text-gray-700 font-bold">状态</text>
</view>
<view class="table-col-time">
<text class="text-sm text-gray-700 font-bold">创建时间</text>
</view>
</view>
<!-- 表格内容 -->
<view v-for="(item, index) in dataList"
:key="item.id"
class="flex flex-row border-b border-gray-200 bg-white"
:class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-col-checkbox" @click.stop="toggleSelect(item.id)">
<checkbox :checked="isSelected(item.id)"
:value="item.id"
@click.stop="toggleSelect(item.id)" />
</view>
<view class="table-col-id">
<text class="text-sm text-gray-800">{{ item.id }}</text>
</view>
<view class="table-col-name">
<text class="text-sm text-gray-800">{{ item.name }}</text>
</view>
<view class="table-col-age">
<text class="text-sm text-gray-800">{{ item.age }}</text>
</view>
<view class="table-col-email">
<text class="text-sm text-gray-800">{{ item.email }}</text>
</view>
<view class="table-col-status">
<text class="px-2 py-1 rounded text-xs"
:class="item.status == 'active' ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'">
{{ item.status == "active" ? "活跃" : "非活跃" }}
</text>
</view>
<view class="table-col-time">
<text class="text-sm text-gray-800">{{ formatTime(item.created_at) }}</text>
</view>
</view>
</view>
</view>
</view>
<!-- 日志区域:右侧区域下半部分,高度约 50%,内部可滚动 -->
<view class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5">
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
操作日志
</text>
<button class="btn btn-danger text-xs" @click="clearLogs">
清空日志
</button>
</view>
<!-- 日志内容 -->
<view class="flex-1 overflow-hidden min-h-0">
<view v-if="logs.length === 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无日志</text>
</view>
<view v-else class="flex flex-col border border-gray-200 rounded overflow-hidden bg-white shadow-sm">
<!-- 表头 -->
<view class="flex flex-row bg-gray-100 border-b-2 border-gray-300">
<view class="table-log-time">
<text class="text-xs text-gray-700 font-bold">时间</text>
</view>
<view class="table-log-message">
<text class="text-xs text-gray-700 font-bold">操作内容</text>
</view>
</view>
<!-- 表格内容 -->
<view v-for="(log, index) in logs"
:key="index"
class="flex flex-row border-b border-gray-200 bg-white"
:class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-log-time">
<text class="text-xs text-indigo-500 font-medium">{{ log.time }}</text>
</view>
<view class="table-log-message">
<text class="text-xs text-gray-800">{{ log.message }}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
import { get } from "@/utils/common.uts";
// 使用 SqliteStore,基于 SQLite 的本地存储方案
import SqliteStore from "@/utils/sqlite-store.uts";
import { get } from "@/utils/common.uts";
// 定义用户数据类型
type UserData = {
id: string;
name: string;
age: number;
created_at: number;
email: string;
id: string;
name: string;
status: string;
created_at: number;
updated_at: number;
};
......@@ -248,8 +274,8 @@ const isLoading = ref<boolean>(false);
// 日志列表
type LogItem = {
time: string;
message: string;
time: string;
};
const logs = ref<LogItem[]>([]);
......@@ -269,7 +295,7 @@ const addLog = (message: string) => {
// UTS 需要显式声明类型,避免类型推断为 UTSJSONObject
const logItem: LogItem = {
time: timeStr,
message: message
message
};
logs.value.push(logItem);
// 限制日志数量
......@@ -280,12 +306,11 @@ const addLog = (message: string) => {
// 刷新数据列表
const refreshData = () => {
isLoading.value = true;
isLoading.value = true;
userStore.select((results) => {
const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) {
const row = results[i];
for (const row of results) {
// 使用 get() 辅助函数安全访问属性,避免 UTS 编译器 error18
newList.push({
id: get(row, "id", "") as string,
......@@ -296,13 +321,13 @@ const refreshData = () => {
created_at: get(row, "created_at", 0) as number,
updated_at: get(row, "updated_at", 0) as number
} as UserData);
}
dataList.value = newList;
}
dataList.value = newList;
isLoading.value = false;
addLog(`刷新成功,共 ${newList.length} 条数据`);
}, (err) => {
addLog(`刷新数据失败: ${JSON.stringify(err)}`);
isLoading.value = false;
isLoading.value = false;
});
};
......@@ -333,9 +358,9 @@ const handleInsert = () => {
const age = Math.floor(Math.random() * 30) + 18;
userStore.insert({
name: names[randomIndex],
age: age,
email: emails[randomIndex],
name: names[randomIndex],
age,
email: emails[randomIndex],
status: Math.random() > 0.5 ? "active" : "inactive"
}, (id) => {
addLog(`插入成功: ID=${id}, 姓名=${names[randomIndex]}`);
......@@ -358,10 +383,10 @@ const handleQuery = () => {
const randomRow = results[Math.floor(Math.random() * results.length)] as UTSJSONObject;
const name = randomRow.get("name") as string;
addLog(`查询成功: 找到 ${results.length} 条记录,示例: ${name}`);
} else {
addLog("查询结果: 暂无数据");
}
refreshData();
} else {
addLog("查询结果: 暂无数据");
}
refreshData();
},
(err: any) => {
addLog(`查询失败: ${err}`);
......@@ -387,11 +412,11 @@ const handleUpdate = () => {
},
(err: any) => {
addLog(`更新失败: ${err}`);
}
}
);
} else {
addLog("更新失败: 暂无数据");
}
} else {
addLog("更新失败: 暂无数据");
}
},
(err: any) => {
addLog(`查询失败: ${err}`);
......@@ -422,7 +447,7 @@ const toggleSelect = (id: string) => {
// 检查是否全选
const isAllSelected = (): boolean => {
if (dataList.value.length == 0) return false;
if (dataList.value.length === 0) return false;
return selectedIds.value.length == dataList.value.length && selectedIds.value.length > 0;
};
......@@ -447,7 +472,7 @@ const toggleSelectAll = () => {
const handleDeleteSelected = () => {
const ids = selectedIds.value;
if (ids.length == 0) {
if (ids.length === 0) {
addLog("请先选择要删除的数据");
return;
}
......@@ -458,8 +483,8 @@ const handleDeleteSelected = () => {
ids,
(res: any) => {
addLog(`删除选中完成: 成功删除 ${ids.length} 条记录`);
selectedIds.value = [];
refreshData();
selectedIds.value = [];
refreshData();
},
(err: any) => {
addLog(`删除失败: ${err}`);
......@@ -472,22 +497,22 @@ const handleQueryAdults = () => {
userStore.select(
(results) => {
const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) {
const row = results[i] as UTSJSONObject;
for (const result of results) {
const row = result as UTSJSONObject;
const age = row.get("age") as number;
if (age >= 18) {
newList.push({
id: row.get("id") as string,
name: row.get("name") as string,
age: age,
age,
email: row.get("email") as string,
status: row.get("status") as string,
created_at: row.get("created_at") as number,
updated_at: row.get("updated_at") as number
} as UserData);
}
}
dataList.value = newList;
}
dataList.value = newList;
addLog(`查询成年人(年龄>=18): 找到 ${newList.length} 条记录`);
},
(err: any) => {
......@@ -500,8 +525,8 @@ const handleQueryActive = () => {
userStore.select(
(results) => {
const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) {
const row = results[i] as UTSJSONObject;
for (const result of results) {
const row = result as UTSJSONObject;
const status = row.get("status") as string;
if (status == "active") {
newList.push({
......@@ -509,13 +534,13 @@ const handleQueryActive = () => {
name: row.get("name") as string,
age: row.get("age") as number,
email: row.get("email") as string,
status: status,
status,
created_at: row.get("created_at") as number,
updated_at: row.get("updated_at") as number
} as UserData);
}
}
dataList.value = newList;
}
dataList.value = newList;
addLog(`查询活跃用户: 找到 ${newList.length} 条记录`);
},
(err: any) => {
......@@ -528,22 +553,22 @@ const handleQueryByEmail = () => {
userStore.select(
(results) => {
const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) {
const row = results[i] as UTSJSONObject;
for (const result of results) {
const row = result as UTSJSONObject;
const email = row.get("email") as string;
if (email.indexOf("example") != -1) {
newList.push({
id: row.get("id") as string,
name: row.get("name") as string,
age: row.get("age") as number,
email: email,
email,
status: row.get("status") as string,
created_at: row.get("created_at") as number,
updated_at: row.get("updated_at") as number
} as UserData);
}
}
dataList.value = newList;
}
dataList.value = newList;
addLog(`按邮箱查询(包含example): 找到 ${newList.length} 条记录`);
},
(err: any) => {
......@@ -568,8 +593,8 @@ const handleBatchInsert = () => {
userStore.insertMany(
newUsers,
(ids) => {
addLog(`批量插入: 成功插入 ${ids.length} 条记录`);
refreshData();
addLog(`批量插入: 成功插入 ${ids.length} 条记录`);
refreshData();
},
(err: any) => {
addLog(`批量插入失败: ${err}`);
......@@ -585,25 +610,25 @@ const handleBatchDelete = () => {
userStore.select(
(results) => {
const idsToDelete: string[] = [];
for (let i = 0; i < results.length; i++) {
const row = results[i] as UTSJSONObject;
for (const result of results) {
const row = result as UTSJSONObject;
const age = row.get("age") as number;
if (age < 20) {
idsToDelete.push(row.get("id") as string);
}
}
if (idsToDelete.length == 0) {
addLog(`批量删除: 没有找到符合条件的记录(年龄<20)`);
return;
}
if (idsToDelete.length === 0) {
addLog(`批量删除: 没有找到符合条件的记录(年龄<20)`);
return;
}
userStore.deleteMany(
idsToDelete,
(res: any) => {
addLog(`批量删除成功: 删除了 ${idsToDelete.length} 条记录`);
selectedIds.value = [];
refreshData();
selectedIds.value = [];
refreshData();
},
(err: any) => {
addLog(`批量删除失败: ${err}`);
......@@ -612,7 +637,7 @@ const handleBatchDelete = () => {
},
(err: any) => {
addLog(`查询失败: ${err}`);
}
}
);
};
......@@ -645,14 +670,14 @@ const handleLargeBatchInsert = () => {
}
userStore.insertMany(allUsers, (ids) => {
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
addLog(`大数据批量插入完成: 成功插入 ${ids.length} 条记录,耗时 ${duration} 秒`);
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
addLog(`大数据批量插入完成: 成功插入 ${ids.length} 条记录,耗时 ${duration} 秒`);
isInserting.value = false;
refreshData();
refreshData();
}, (err) => {
addLog(`大数据批量插入失败: ${JSON.stringify(err)}`);
isInserting.value = false;
isInserting.value = false;
});
};
......@@ -679,8 +704,8 @@ const handleCount = () => {
const handleClear = () => {
userStore.clear(
(res: any) => {
addLog("清空数据: 所有记录已删除");
refreshData();
addLog("清空数据: 所有记录已删除");
refreshData();
},
(err: any) => {
addLog(`清空数据失败: ${err}`);
......@@ -698,7 +723,7 @@ onMounted(() => {
// 初始化数据库
userStore.init(() => {
console.log("[Demo] 数据库初始化完成");
refreshData();
refreshData();
});
});
</script>
......
<template>
<view>
<image class="image" :fade-show="true" mode="widthFix" :src="imageSrc"></image>
<video
class="video"
:src="src"
controls
autoplay
style="width: 100%; height: 300px"
></video>
</view>
<view>
<image class="image"
:fade-show="true"
mode="widthFix"
:src="imageSrc">
</image>
<video autoplay
class="video"
controls
:src="src"
style="width: 100%; height: 300px">
</video>
</view>
</template>
<script setup lang="uts">
const src =ref('https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4')
const imageSrc =ref('https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg')
const src =ref("https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4");
const imageSrc =ref("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg");
</script>
<template>
<!-- #ifdef APP -->
<scroll-view style="flex: 1" scroll-y="true">
<!-- #endif -->
<view class="content flex-col">
<view class="search-box flex">
<view class="form-item form-item-input">
<view class="form-item-box align-center">
<input
:maxlength="20"
v-model="searchText"
class="input flex-1"
placeholder="请输入车架号"
@focus="focusIndex = 0"
@blur="resetFocusIndex"
placeholder-class="placeholder"
/>
<text class="sprite-icon icon-vinScan" @click.stop="scan">📷</text>
</view>
</view>
<view class="btn search" @click="search"><text class="btn-text">查询</text></view>
<view class="btn reset" @click="reset"><text class="btn-text">重置</text></view>
</view>
<!-- #ifdef APP -->
<scroll-view scroll-y="true" style="flex: 1">
<!-- #endif -->
<view class="content flex-col">
<view class="search-box flex">
<view class="form-item form-item-input">
<view class="form-item-box align-center">
<input v-model="searchText"
class="input flex-1"
:maxlength="20"
placeholder="请输入车架号"
placeholder-class="placeholder"
@blur="resetFocusIndex"
@focus="focusIndex = 0" />
<text class="sprite-icon icon-vinScan" @click.stop="scan">📷</text>
</view>
</view>
<view class="btn search" @click="search">
<text class="btn-text">查询</text>
</view>
<view class="btn reset" @click="reset">
<text class="btn-text">重置</text>
</view>
</view>
<view class="list-box">
<!-- 类型标签页组件 -->
<type-tab-component :typeList="typeList" :isShowCount="true" :tabIndex="tabIndex" @tabClick="tabBarClick"></type-tab-component>
<view class="list-box">
<!-- 类型标签页组件 -->
<TypeTabComponent :is-show-count="true"
:tab-index="tabIndex"
:type-list="typeList"
@tab-click="tabBarClick">
</TypeTabComponent>
<!-- z-paging-x 列表 -->
<z-paging-x
ref="paging"
v-model="list"
list-is="scroll-view"
@query="getCheckReportPageList"
>
<template #empty>
<view class="nothing flex">
<text class="noDataImg">📋</text>
<text>暂无报告管理</text>
</view>
</template>
<!-- z-paging-x 列表 -->
<z-paging-x ref="paging"
v-model="list"
list-is="scroll-view"
@query="getCheckReportPageList">
<template #empty>
<view class="nothing flex">
<text class="noDataImg">📋</text>
<text>暂无报告管理</text>
</view>
</template>
<!-- 列表容器,按照原项目结构(放在默认插槽中) -->
<view class="item-list">
<view
v-for="(i, index) in list"
:key="index"
class="item flex-col"
@click="toDetail(i)"
>
<view class="flex align-center justify-between mb-28">
<view class="flex align-center">
<view class="sprite-icon" :class="getReportType(i) === 0 ? 'icon-accident' : 'icon-weibao'">
<text>{{ getReportType(i) === 0 ? '🚗' : '🔧' }}</text>
</view>
<text class="reportTypeName">{{ getReportType(i) === 0 ? '事故报告' : '维保报告' }}</text>
</view>
<text class="reportStatus" :class="['reportStatus' + getStatus(i)]">{{ getStatusText(getStatus(i)) }}</text>
</view>
<view class="cell flex align-center mb-28">
<text class="label">车架号</text>
<text class="value">{{ getVin(i) }}</text>
</view>
<view class="cell flex align-center mb-28">
<text class="label">报告时间</text>
<text class="value">{{ formatTime(getAcquireTime(i)) }}</text>
</view>
</view>
</view>
<!-- 列表容器,按照原项目结构(放在默认插槽中) -->
<view class="item-list">
<view v-for="(i, index) in list"
:key="index"
class="item flex-col"
@click="toDetail(i)">
<view class="flex align-center justify-between mb-28">
<view class="flex align-center">
<view class="sprite-icon" :class="getReportType(i) === 0 ? 'icon-accident' : 'icon-weibao'">
<text>{{ getReportType(i) === 0 ? '🚗' : '🔧' }}</text>
</view>
<text class="reportTypeName">{{ getReportType(i) === 0 ? '事故报告' : '维保报告' }}</text>
</view>
<text class="reportStatus" :class="[`reportStatus${ getStatus(i)}`]">{{ getStatusText(getStatus(i)) }}</text>
</view>
<view class="cell flex align-center mb-28">
<text class="label">车架号</text>
<text class="value">{{ getVin(i) }}</text>
</view>
<view class="cell flex align-center mb-28">
<text class="label">报告时间</text>
<text class="value">{{ formatTime(getAcquireTime(i)) }}</text>
</view>
</view>
</view>
</z-paging-x>
</view>
</z-paging-x>
</view>
<!-- 新增报告按钮 -->
<view class="addBtn" @click.stop="openShowPopup">
<view class="addBtn-icon">
<text class="sprite-icon icon-addReport">➕</text>
<text class="addBtn-text">新增报告</text>
</view>
</view>
</view>
<!-- 新增报告按钮 -->
<view class="addBtn" @click.stop="openShowPopup">
<view class="addBtn-icon">
<text class="sprite-icon icon-addReport">➕</text>
<text class="addBtn-text">新增报告</text>
</view>
</view>
</view>
<!-- 新增报告弹窗 -->
<PublishPopup ref="publishPopup" type="center" :isShowFooter="false" :showTitle="false">
<template #content>
<view class="popup-content">
<view class="popup-top-box flex align-center">
<text class="popup-top-box-title">新增报告</text>
<view class="popup-top-box-close" @click.stop="closePublishPopup">
<text class="sprite-icon icon-evaluationClose">✕</text>
</view>
</view>
<view class="flex popup-content-item">
<view class="popup-content-left flex-shrink-0">
<view class="flex align-center grayLabel">
<text class="sprite-icon icon-accidentIcon">📊</text>
<text>报告类型</text>
</view>
<view>
<view class="flex align-start mb-28 tabItem" :class="{ active0: addParams.reportType === 0 }" @click="changeReportType(0)">
<text class="sprite-icon icon-accident">🚗</text>
<view>
<text class="title">事故报告</text>
<text class="desc">含出险,理赔记录</text>
</view>
</view>
<view class="flex align-start tabItem" :class="{ active1: addParams.reportType === 1 }" @click="changeReportType(1)">
<text class="sprite-icon icon-weibao">🔧</text>
<view>
<text class="title">维保报告</text>
<text class="desc">含维修、保养记录</text>
</view>
</view>
</view>
</view>
<view class="popup-content-right flex-1">
<view class="flex align-center grayLabel">
<text class="sprite-icon icon-carInfo">🚙</text>
<text>车辆资料</text>
</view>
<view class="upload-box box">
<view class="title">
<text>车架号(VIN)</text>
<text class="required">*</text>
</view>
<view class="flex vinInput justify-between">
<input
:maxlength="17"
v-model="addParams.vin"
class="input flex-1"
placeholder="请输入17位VIN"
placeholder-class="placeholder"
@blur="vinBlur"
/>
<text class="sprite-icon icon-vinScan" @click.stop="scanVin">📷</text>
</view>
</view>
<view class="upload-box box">
<view class="title">
<text>行驶证照片</text>
<text class="required">*</text>
</view>
<view class="img-list flex">
<template v-if="imgList.length < 1">
<view class="img-item upload flex align-center justify-center" @click="chooseImage">
<text class="sprite-icon icon-uploadIcon">📤</text>
<text class="sprite-icon icon-takePhotoIcon">📷</text>
</view>
</template>
<template v-for="(i, index) in imgList" :key="index">
<view class="img-item">
<image :src="i" class="img" mode="aspectFill" @click="previewMedia(i)" />
<view class="del flex" @click="delImage(index)">
<text style="color: #fff; font-size: 20rpx;">✕</text>
</view>
</view>
</template>
</view>
</view>
<view class="flex align-center justify-between mt-108">
<view class="flex align-center">
<checkbox
value="cb"
:checked="isConfirmChecked"
@click="checkboxChange"
style="transform: scale(0.6)"
/>
<text class="checkboxLabel">确认信息真实有效</text>
</view>
<view :class="['btn flex justify-center', { disabled: !canSubmit }]" @click="comfirm"><text class="btn-text">提交申请</text></view>
</view>
</view>
</view>
</view>
</template>
</PublishPopup>
<!-- #ifdef APP -->
</scroll-view>
<!-- #endif -->
<!-- 新增报告弹窗 -->
<PublishPopup ref="publishPopup"
:is-show-footer="false"
:show-title="false"
type="center">
<template #content>
<view class="popup-content">
<view class="popup-top-box flex align-center">
<text class="popup-top-box-title">新增报告</text>
<view class="popup-top-box-close" @click.stop="closePublishPopup">
<text class="sprite-icon icon-evaluationClose">✕</text>
</view>
</view>
<view class="flex popup-content-item">
<view class="popup-content-left flex-shrink-0">
<view class="flex align-center grayLabel">
<text class="sprite-icon icon-accidentIcon">📊</text>
<text>报告类型</text>
</view>
<view>
<view class="flex align-start mb-28 tabItem"
:class="{ active0: addParams.reportType === 0 }"
@click="changeReportType(0)">
<text class="sprite-icon icon-accident">🚗</text>
<view>
<text class="title">事故报告</text>
<text class="desc">含出险,理赔记录</text>
</view>
</view>
<view class="flex align-start tabItem"
:class="{ active1: addParams.reportType === 1 }"
@click="changeReportType(1)">
<text class="sprite-icon icon-weibao">🔧</text>
<view>
<text class="title">维保报告</text>
<text class="desc">含维修、保养记录</text>
</view>
</view>
</view>
</view>
<view class="popup-content-right flex-1">
<view class="flex align-center grayLabel">
<text class="sprite-icon icon-carInfo">🚙</text>
<text>车辆资料</text>
</view>
<view class="upload-box box">
<view class="title">
<text>车架号(VIN)</text>
<text class="required">*</text>
</view>
<view class="flex vinInput justify-between">
<input v-model="addParams.vin"
class="input flex-1"
:maxlength="17"
placeholder="请输入17位VIN"
placeholder-class="placeholder"
@blur="vinBlur" />
<text class="sprite-icon icon-vinScan" @click.stop="scanVin">📷</text>
</view>
</view>
<view class="upload-box box">
<view class="title">
<text>行驶证照片</text>
<text class="required">*</text>
</view>
<view class="img-list flex">
<template v-if="imgList.length === 0">
<view class="img-item upload flex align-center justify-center" @click="chooseImage">
<text class="sprite-icon icon-uploadIcon">📤</text>
<text class="sprite-icon icon-takePhotoIcon">📷</text>
</view>
</template>
<template v-for="(i, index) in imgList" :key="index">
<view class="img-item">
<image class="img"
mode="aspectFill"
:src="i"
@click="previewMedia(i)" />
<view class="del flex" @click="delImage(index)">
<text style="color: #fff; font-size: 20rpx;">✕</text>
</view>
</view>
</template>
</view>
</view>
<view class="flex align-center justify-between mt-108">
<view class="flex align-center">
<checkbox :checked="isConfirmChecked"
style="transform: scale(0.6)"
value="cb"
@click="checkboxChange" />
<text class="checkboxLabel">确认信息真实有效</text>
</view>
<view class="btn flex justify-center"
:class="[{ disabled: !canSubmit }]"
@click="comfirm">
<text class="btn-text">提交申请</text>
</view>
</view>
</view>
</view>
</view>
</template>
</PublishPopup>
<!-- #ifdef APP -->
</scroll-view>
<!-- #endif -->
</template>
<script setup lang="uts">
import { ref, computed, onMounted, nextTick, type ComponentPublicInstance } from 'vue';
import TypeTabComponent from '@/components/evaluationForm/TypeTabComponent.uvue';
import PublishPopup from '@/components/PublishPopup.uvue';
import { get } from '@/utils/common.uts';
import type { ComponentPublicInstance } from "vue";
import { computed, nextTick, onMounted, ref } from "vue";
import TypeTabComponent from "@/components/evaluationForm/TypeTabComponent.uvue";
import PublishPopup from "@/components/PublishPopup.uvue";
import { get } from "@/utils/common.uts";
// 类型定义
type TypeTabItem = {
tabName: string;
count: number;
key: string;
tabName: string;
};
type ReportItem = {
acquireTime: number;
id: string;
reportType: number;
vin: string;
acquireTime: number;
status: number;
vin: string;
};
type AddReportParams = {
licenseUrl: string;
reportType: number;
vin: string;
licenseUrl: string;
};
// 常量
const ORDER_STATUS = {
'0': '待审核',
'1': '已通过',
'2': '已拒绝',
'3': '已完成'
"0": "待审核",
"1": "已通过",
"2": "已拒绝",
"3": "已完成"
};
// 响应式数据
const typeList = ref<TypeTabItem[]>([
{ tabName: '全部', count: 0, key: '' },
{ tabName: '事故报告', count: 0, key: '0' },
{ tabName: '维保报告', count: 0, key: '1' }
{ tabName: "全部", count: 0, key: "" },
{ tabName: "事故报告", count: 0, key: "0" },
{ tabName: "维保报告", count: 0, key: "1" }
]);
const tabIndex = ref<number>(0);
const searchText = ref<string>('');
const searchText = ref<string>("");
const focusIndex = ref<number>(-1);
const list = ref<any[]>([]);
const addParams = ref<AddReportParams>({
reportType: 0,
vin: '',
licenseUrl: ''
vin: "",
licenseUrl: ""
});
const imgList = ref<string[]>([]);
const isConfirmChecked = ref<boolean>(false);
......@@ -241,57 +256,56 @@ const publishPopup = ref<ComponentPublicInstance | null>(null);
// Mock 数据
const mockData: ReportItem[] = [
{
id: '1',
id: "1",
reportType: 0,
vin: 'SALWA2BU6LA713964',
acquireTime: Date.now() - 86400000,
vin: "SALWA2BU6LA713964",
acquireTime: Date.now() - 86_400_000,
status: 0
},
{
id: '2',
id: "2",
reportType: 1,
vin: 'WDC0J6EB6KF571271',
acquireTime: Date.now() - 172800000,
vin: "WDC0J6EB6KF571271",
acquireTime: Date.now() - 172_800_000,
status: 1
},
{
id: '3',
id: "3",
reportType: 0,
vin: 'LFMCM1CX9L0095398',
acquireTime: Date.now() - 259200000,
vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259_200_000,
status: 3
},
{
id: '4',
{
id: "4",
reportType: 0,
vin: 'LFMCM1CX9L0095398',
acquireTime: Date.now() - 259200000,
vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259_200_000,
status: 3
},
{
id: '5',
id: "5",
reportType: 0,
vin: 'LFMCM1CX9L0095398',
acquireTime: Date.now() - 259200000,
vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259_200_000,
status: 3
},
{
id: '6',
id: "6",
reportType: 0,
vin: 'LFMCM1CX9L0095398',
acquireTime: Date.now() - 259200000,
vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259_200_000,
status: 3
}
];
// 根据 mockData 计算各类型数量,保证 tab count 与实际数据一致
const updateTypeCount = () => {
let all = mockData.length;
const all = mockData.length;
let accident = 0;
let weibo = 0;
for (let i = 0; i < mockData.length; i++) {
const item = mockData[i];
for (const item of mockData) {
if (item.reportType == 0) {
accident = accident + 1;
} else if (item.reportType == 1) {
......@@ -301,12 +315,10 @@ const updateTypeCount = () => {
// 避免 UTS 推断为 UTSArray<UTSJSONObject>,显式构造 TypeTabItem[] 再赋值
const newList: TypeTabItem[] = [];
newList.push({ tabName: '全部', count: all, key: '' });
newList.push({ tabName: '事故报告', count: accident, key: '0' });
newList.push({ tabName: '维保报告', count: weibo, key: '1' });
newList.push({ tabName: "全部", count: all, key: "" }, { tabName: "事故报告", count: accident, key: "0" }, { tabName: "维保报告", count: weibo, key: "1" });
typeList.value = newList;
console.log('[updateTypeCount]', {
console.log("[updateTypeCount]", {
all,
accident,
weibo,
......@@ -317,7 +329,7 @@ const updateTypeCount = () => {
// 计算属性
const canSubmit = computed<boolean>(() => {
return addParams.value.vin !== '' && imgList.value.length > 0 && isConfirmChecked.value;
return addParams.value.vin !== "" && imgList.value.length > 0 && isConfirmChecked.value;
});
// 辅助方法:安全访问 any 类型的属性
......@@ -339,11 +351,11 @@ const getAcquireTime = (item: any): number => {
// 获取状态文本
const getStatusText = (status: number): string => {
if (status == 0) return '待审核';
if (status == 1) return '已通过';
if (status == 2) return '已拒绝';
if (status == 3) return '已完成';
return '未知';
if (status == 0) return "待审核";
if (status == 1) return "已通过";
if (status == 2) return "已拒绝";
if (status == 3) return "已完成";
return "未知";
};
// z-paging-x 加载数据(本地 mock)
......@@ -372,20 +384,20 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => {
const end = start + pageSize;
const pageData = filteredData.slice(start, end);
console.log('[getCheckReportPageList]', {
console.log("[getCheckReportPageList]", {
pageNo,
pageSize,
tabIndex: tabIndex.value,
filteredDataLength: filteredData.length,
pageDataLength: pageData.length,
pageData: pageData
pageData
});
// 将请求结果通过 complete 传给 z-paging-x 处理,同时也代表请求结束,这一行必须调用
// 按照文档:(this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(res['data'] as any[])
// 在 uni-app x Composition API 中,使用 $callMethod 调用组件方法
if (paging.value != null) {
paging.value.$callMethod('complete', pageData as any[]);
paging.value.$callMethod("complete", pageData as any[]);
// (this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(pageData as any[])
}
}, 300);
......@@ -394,13 +406,13 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => {
// 查询
const search = () => {
if (paging.value != null) {
paging.value.$callMethod('reload');
paging.value.$callMethod("reload");
}
};
// 重置
const reset = () => {
searchText.value = '';
searchText.value = "";
search();
};
......@@ -416,7 +428,7 @@ const toDetail = (item: any) => {
const reportItem = item as ReportItem;
uni.showToast({
title: `查看报告: ${reportItem.vin}`,
icon: 'none'
icon: "none"
});
};
......@@ -424,10 +436,10 @@ const toDetail = (item: any) => {
const formatTime = (timestamp: number): string => {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}`;
};
......@@ -439,29 +451,29 @@ const resetFocusIndex = () => {
// 扫描识别
const scan = () => {
uni.showToast({
title: 'VIN识别功能待实现',
icon: 'none'
title: "VIN识别功能待实现",
icon: "none"
});
};
const scanVin = () => {
uni.showToast({
title: 'VIN识别功能待实现',
icon: 'none'
title: "VIN识别功能待实现",
icon: "none"
});
};
// 打开弹窗
const openShowPopup = () => {
if (publishPopup.value != null) {
publishPopup.value.$callMethod('openPopup');
publishPopup.value.$callMethod("openPopup");
}
};
// 关闭弹窗
const closePublishPopup = () => {
if (publishPopup.value != null) {
publishPopup.value.$callMethod('closePopup');
publishPopup.value.$callMethod("closePopup");
}
};
......@@ -473,10 +485,10 @@ const changeReportType = (type: number) => {
// VIN输入验证
const vinBlur = () => {
const vin = addParams.value.vin;
if (vin != '' && vin.length != 17) {
if (vin != "" && vin.length != 17) {
uni.showToast({
title: 'VIN码必须为17位',
icon: 'none'
title: "VIN码必须为17位",
icon: "none"
});
}
};
......@@ -486,8 +498,8 @@ const chooseImage = () => {
uni.chooseImage({
count: 1,
success: (res: any) => {
const tempFilePaths = get(res, 'tempFilePaths');
if (tempFilePaths != null && tempFilePaths instanceof Array) {
const tempFilePaths = get(res, "tempFilePaths");
if (tempFilePaths != null && Array.isArray(tempFilePaths)) {
const paths = tempFilePaths as string[];
if (paths.length > 0) {
imgList.value.push(paths[0]);
......@@ -520,14 +532,14 @@ const comfirm = () => {
if (!canSubmit.value) return;
uni.showToast({
title: '提交成功(模拟)',
icon: 'success'
title: "提交成功(模拟)",
icon: "success"
});
addParams.value = {
reportType: 0,
vin: '',
licenseUrl: ''
vin: "",
licenseUrl: ""
} as AddReportParams;
imgList.value = [];
isConfirmChecked.value = false;
......@@ -542,7 +554,7 @@ onMounted(() => {
// 首次进入页面主动触发一次加载,避免必须点"查询"才看到列表
nextTick(() => {
if (paging.value != null) {
paging.value.$callMethod('reload');
paging.value.$callMethod("reload");
}
});
// TODO: 将来接入 uni.$track
......
<template>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<text class="text-3xl font-bold text-white mb-2 block">权限申请示例</text>
<text class="text-base text-white opacity-90 block">使用 permission-handler-plus 插件</text>
</view>
<scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<text class="text-3xl font-bold text-white mb-2 block">权限申请示例</text>
<text class="text-base text-white opacity-90 block">使用 permission-handler-plus 插件</text>
</view>
<!-- 权限列表 -->
<view class="flex flex-col">
<view
v-for="permission in permissions"
:key="permission.name"
class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col"
>
<!-- 权限名称和状态 -->
<view class="flex flex-row items-center justify-between mb-3">
<view class="flex flex-row items-center">
<text class="text-2xl mr-3">{{ permission.icon }}</text>
<view class="flex flex-col">
<text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text>
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view>
</view>
<view
class="px-3 py-1 rounded-full"
:class="'status-' + permission.status"
>
<text class="text-xs font-medium" :class="'status-text-' + permission.status">
{{ getStatusText(permission.status) }}
</text>
</view>
</view>
<!-- 权限列表 -->
<view class="flex flex-col">
<view v-for="permission in permissions"
:key="permission.name"
class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
<!-- 权限名称和状态 -->
<view class="flex flex-row items-center justify-between mb-3">
<view class="flex flex-row items-center">
<text class="text-2xl mr-3">{{ permission.icon }}</text>
<view class="flex flex-col">
<text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text>
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view>
</view>
<view class="px-3 py-1 rounded-full"
:class="`status-${ permission.status}`">
<text class="text-xs font-medium" :class="`status-text-${ permission.status}`">
{{ getStatusText(permission.status) }}
</text>
</view>
</view>
<!-- 操作按钮 -->
<view class="flex flex-row flex-wrap">
<button
class="btn btn-primary mr-2 mb-2"
@click="checkPermission(permission)"
>
检查权限
</button>
<button
class="btn btn-success mr-2 mb-2"
@click="requestPermission(permission)"
:disabled="permission.status === 'granted'"
>
申请权限
</button>
</view>
</view>
</view>
<!-- 操作按钮 -->
<view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2"
@click="checkPermission(permission)">
检查权限
</button>
<button class="btn btn-success mr-2 mb-2"
:disabled="permission.status === 'granted'"
@click="requestPermission(permission)">
申请权限
</button>
</view>
</view>
</view>
<!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm mt-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col">
<view
v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200"
>
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button
class="btn btn-secondary mt-3"
@click="clearLogs"
>
清空日志
</button>
</view>
</view>
</scroll-view>
<!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm mt-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view class="flex flex-col"
scroll-y="true"
style="max-height: 300px">
<view v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200">
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button class="btn btn-secondary mt-3"
@click="clearLogs">
清空日志
</button>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
// 统一导入,编译器会自动根据平台选择对应的实现
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { get } from "@/utils/common.uts";
type PermissionStatus = "unknown" | "granted" | "denied" | "restricted" | "limited" | "permanentlyDenied" | "provisional";
type PermissionStatus = "denied" | "granted" | "limited" | "permanentlyDenied" | "provisional" | "restricted" | "unknown";
type Permission = {
name: string;
displayName: string;
desc: string;
displayName: string;
icon: string;
name: string;
status: PermissionStatus;
};
......@@ -187,7 +178,7 @@ const checkPermission = (permission: Permission) => {
// 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) {
if (index !== -1) {
// 将插件返回的状态字符串转换为我们的状态类型
let status: PermissionStatus = "unknown";
if (result == "granted") {
......@@ -229,7 +220,7 @@ const requestPermission = (permission: Permission) => {
// 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) {
if (index !== -1) {
let status: PermissionStatus = "unknown";
if (statusStr == "granted") {
status = "granted";
......
<template>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<text class="text-3xl font-bold text-white mb-2 block">录音示例</text>
<text class="text-base text-white opacity-90 block">演示 uts-recorder 插件的基础用法</text>
</view>
<scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<text class="text-3xl font-bold text-white mb-2 block">录音示例</text>
<text class="text-base text-white opacity-90 block">演示 uts-recorder 插件的基础用法</text>
</view>
<!-- 权限提示区域 -->
<view v-if="!hasPermission" class="bg-yellow-50 rounded-lg p-4 mb-4 flex-col">
<view class="flex flex-row items-center mb-2">
<text class="text-xl mr-2">⚠️</text>
<text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text>
</view>
<text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text>
<button
class="btn btn-warning"
@click="requestRecordPermission"
>
申请麦克风权限
</button>
</view>
<!-- 权限提示区域 -->
<view v-if="!hasPermission" class="bg-yellow-50 rounded-lg p-4 mb-4 flex-col">
<view class="flex flex-row items-center mb-2">
<text class="text-xl mr-2">⚠️</text>
<text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text>
</view>
<text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text>
<button class="btn btn-warning"
@click="requestRecordPermission">
申请麦克风权限
</button>
</view>
<!-- 操作区域 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text>
<view class="flex flex-row flex-wrap">
<button
class="btn btn-primary mr-2 mb-2"
@click="startRecord"
:disabled="!hasPermission"
>
开始录音
</button>
<button
class="btn btn-secondary mr-2 mb-2"
@click="stopRecord"
>
停止录音
</button>
</view>
<view v-if="recordStatus !== ''" class="mt-2">
<text class="text-sm text-gray-600 block">{{ recordStatus }}</text>
</view>
</view>
<!-- 操作区域 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text>
<view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2"
:disabled="!hasPermission"
@click="startRecord">
开始录音
</button>
<button class="btn btn-secondary mr-2 mb-2"
@click="stopRecord">
停止录音
</button>
</view>
<view v-if="recordStatus !== ''" class="mt-2">
<text class="text-sm text-gray-600 block">{{ recordStatus }}</text>
</view>
</view>
<!-- 录音列表 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">
录音列表
<text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text>
</text>
<!-- 录音列表 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">
录音列表
<text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text>
</text>
<view v-if="recordList.length == 0" class="flex flex-row items-center">
<text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text>
</view>
<view v-if="recordList.length === 0" class="flex flex-row items-center">
<text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text>
</view>
<scroll-view
v-else
style="max-height: 400px"
scroll-y="true"
class="flex flex-col"
>
<view
v-for="record in recordList"
:key="record.id"
class="flex flex-col mb-3 pb-3 border-b border-gray-200"
>
<!-- 录音信息 -->
<view class="flex flex-row items-center justify-between mb-2">
<view class="flex flex-col">
<text class="text-sm font-semibold text-gray-800 block">录音 #{{ record.id }}</text>
<text class="text-xs text-gray-500 block">时长: {{ formatDuration(record.duration) }}</text>
<text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text>
</view>
<view class="flex flex-row">
<button
v-if="!record.isPlaying"
class="btn btn-primary mr-2"
@click="playRecord(record)"
>
播放
</button>
<button
v-else
class="btn btn-secondary mr-2"
@click="stopPlay(record)"
>
停止
</button>
<button
class="btn btn-danger"
@click="deleteRecord(record)"
>
删除
</button>
</view>
</view>
<!-- 文件路径 -->
<text class="text-xs text-gray-400 block" selectable="true">{{ record.filePath }}</text>
</view>
</scroll-view>
</view>
<scroll-view v-else
class="flex flex-col"
scroll-y="true"
style="max-height: 400px">
<view v-for="record in recordList"
:key="record.id"
class="flex flex-col mb-3 pb-3 border-b border-gray-200">
<!-- 录音信息 -->
<view class="flex flex-row items-center justify-between mb-2">
<view class="flex flex-col">
<text class="text-sm font-semibold text-gray-800 block">录音 #{{ record.id }}</text>
<text class="text-xs text-gray-500 block">时长: {{ formatDuration(record.duration) }}</text>
<text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text>
</view>
<view class="flex flex-row">
<button v-if="!record.isPlaying"
class="btn btn-primary mr-2"
@click="playRecord(record)">
播放
</button>
<button v-else
class="btn btn-secondary mr-2"
@click="stopPlay(record)">
停止
</button>
<button class="btn btn-danger"
@click="deleteRecord(record)">
删除
</button>
</view>
</view>
<!-- 文件路径 -->
<text class="text-xs text-gray-400 block" selectable="true">{{ record.filePath }}</text>
</view>
</scroll-view>
</view>
<!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col">
<view
v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200"
>
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button
class="btn btn-secondary mt-3"
@click="clearLogs"
>
清空日志
</button>
</view>
</view>
</scroll-view>
<!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view class="flex flex-col"
scroll-y="true"
style="max-height: 300px">
<view v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200">
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button class="btn btn-secondary mt-3"
@click="clearLogs">
清空日志
</button>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import {
startRecord as uniStartRecord,
stopRecord as uniStopRecord
} from "@/uni_modules/uts-recorder";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { get } from "@/utils/common.uts";
// 录音文件信息类型
type RecordFileInfo = {
id: string;
filePath: string;
duration: number;
createTime: number;
duration: number;
filePath: string;
id: string;
isPlaying: boolean;
};
......@@ -171,7 +155,7 @@ const checkRecordPermission = () => {
hasPermission.value = status == "granted";
addLog(`当前麦克风权限状态: ${status}`);
});
}
};
// 申请录音权限
const requestRecordPermission = () => {
......@@ -184,7 +168,7 @@ const requestRecordPermission = () => {
// result 是一个 Map<string, string>
// 使用 get() 辅助函数访问 Map
const micStatus = get(result, "Microphone") as string | null;
const micStatus = get(result, "Microphone") as null | string;
if (micStatus != null) {
const granted = micStatus == "granted";
hasPermission.value = granted;
......@@ -213,7 +197,7 @@ const requestRecordPermission = () => {
});
}
});
}
};
// 开始录音 - 使用标准 uni API 模式
const startRecord = () => {
......@@ -345,7 +329,7 @@ const stopPlay = (record: RecordFileInfo) => {
const deleteRecord = (record: RecordFileInfo) => {
// 从列表中移除
const index = recordList.value.findIndex(item => item.id == record.id);
if (index > -1) {
if (index !== -1) {
recordList.value.splice(index, 1);
addLog(`已删除录音,剩余 ${recordList.value.length} 条`);
}
......@@ -356,15 +340,15 @@ const formatDuration = (ms: number): string => {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};
// 格式化时间
const formatTime = (timestamp: number): string => {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
return `${hours}:${minutes}:${seconds}`;
};
......
<template>
<!-- #ifdef APP -->
<scroll-view style="flex: 1" class="min-h-screen bg-gray-50">
<!-- #endif -->
<!-- #ifndef APP -->
<view class="min-h-screen bg-gray-50">
<!-- #endif -->
<!-- 头部 -->
<!-- #ifdef APP -->
<view class="bg-blue-500 px-6 py-8">
<text class="text-3xl font-bold text-white mb-2 block">Tailwind CSS 示例</text>
<text class="text-base text-white opacity-90 block">weapp-tailwindcss 多端适配演示</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-blue-500 to-purple-600 px-6 py-8">
<text class="text-3xl font-bold text-white mb-2 block">Tailwind CSS 示例</text>
<text class="text-base text-white opacity-90 block">weapp-tailwindcss 多端适配演示</text>
</view>
<!-- #endif -->
<!-- 内容区域 -->
<view class="px-4 py-6">
<!-- 平台标识 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">当前平台</text>
<view class="flex justify-center">
<!-- #ifdef APP -->
<view class="px-6 py-3 rounded-full bg-blue-500">
<text class="text-white font-semibold">APP 平台</text>
</view>
<!-- #endif -->
<!-- #ifdef MP -->
<view class="px-6 py-3 rounded-full bg-green-500">
<text class="text-white font-semibold">小程序平台</text>
</view>
<!-- #endif -->
<!-- #ifdef H5 -->
<view class="px-6 py-3 rounded-full bg-purple-500">
<text class="text-white font-semibold">H5 平台</text>
</view>
<!-- #endif -->
</view>
</view>
<!-- #ifdef APP -->
<scroll-view class="min-h-screen bg-gray-50" style="flex: 1">
<!-- #endif -->
<!-- #ifndef APP -->
<view class="min-h-screen bg-gray-50">
<!-- #endif -->
<!-- 头部 -->
<!-- #ifdef APP -->
<view class="bg-blue-500 px-6 py-8">
<text class="text-3xl font-bold text-white mb-2 block">Tailwind CSS 示例</text>
<text class="text-base text-white opacity-90 block">weapp-tailwindcss 多端适配演示</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-blue-500 to-purple-600 px-6 py-8">
<text class="text-3xl font-bold text-white mb-2 block">Tailwind CSS 示例</text>
<text class="text-base text-white opacity-90 block">weapp-tailwindcss 多端适配演示</text>
</view>
<!-- #endif -->
<!-- 内容区域 -->
<view class="px-4 py-6">
<!-- 平台标识 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">当前平台</text>
<view class="flex justify-center">
<!-- #ifdef APP -->
<view class="px-6 py-3 rounded-full bg-blue-500">
<text class="text-white font-semibold">APP 平台</text>
</view>
<!-- #endif -->
<!-- #ifdef MP -->
<view class="px-6 py-3 rounded-full bg-green-500">
<text class="text-white font-semibold">小程序平台</text>
</view>
<!-- #endif -->
<!-- #ifdef H5 -->
<view class="px-6 py-3 rounded-full bg-purple-500">
<text class="text-white font-semibold">H5 平台</text>
</view>
<!-- #endif -->
</view>
</view>
<!-- 颜色系统 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">颜色系统</text>
<view class="flex flex-wrap gap-3">
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-blue-500">
<text class="text-white text-xs font-medium">Blue</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-green-500">
<text class="text-white text-xs font-medium">Green</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-red-500">
<text class="text-white text-xs font-medium">Red</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-yellow-500">
<text class="text-white text-xs font-medium">Yellow</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-purple-500">
<text class="text-white text-xs font-medium">Purple</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-pink-500">
<text class="text-white text-xs font-medium">Pink</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-indigo-500">
<text class="text-white text-xs font-medium">Indigo</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-teal-500">
<text class="text-white text-xs font-medium">Teal</text>
</view>
</view>
</view>
<!-- 颜色系统 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">颜色系统</text>
<view class="flex flex-wrap gap-3">
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-blue-500">
<text class="text-white text-xs font-medium">Blue</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-green-500">
<text class="text-white text-xs font-medium">Green</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-red-500">
<text class="text-white text-xs font-medium">Red</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-yellow-500">
<text class="text-white text-xs font-medium">Yellow</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-purple-500">
<text class="text-white text-xs font-medium">Purple</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-pink-500">
<text class="text-white text-xs font-medium">Pink</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-indigo-500">
<text class="text-white text-xs font-medium">Indigo</text>
</view>
<view class="w-20 h-20 rounded-lg flex items-center justify-center bg-teal-500">
<text class="text-white text-xs font-medium">Teal</text>
</view>
</view>
</view>
<!-- 间距系统 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">间距系统</text>
<view class="flex flex-wrap gap-4 items-center">
<view class="p-2 bg-blue-100 rounded flex items-center justify-center">
<text class="text-xs">p-2</text>
</view>
<view class="p-4 bg-blue-200 rounded flex items-center justify-center">
<text class="text-xs">p-4</text>
</view>
<view class="p-6 bg-blue-300 rounded flex items-center justify-center">
<text class="text-xs">p-6</text>
</view>
<view class="p-8 bg-blue-400 rounded flex items-center justify-center">
<text class="text-xs">p-8</text>
</view>
</view>
<view class="mt-4 flex flex-wrap gap-4 items-center">
<view class="m-2 bg-green-100 rounded flex items-center justify-center">
<text class="text-xs">m-2</text>
</view>
<view class="m-4 bg-green-200 rounded flex items-center justify-center">
<text class="text-xs">m-4</text>
</view>
<view class="m-6 bg-green-300 rounded flex items-center justify-center">
<text class="text-xs">m-6</text>
</view>
</view>
</view>
<!-- 间距系统 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">间距系统</text>
<view class="flex flex-wrap gap-4 items-center">
<view class="p-2 bg-blue-100 rounded flex items-center justify-center">
<text class="text-xs">p-2</text>
</view>
<view class="p-4 bg-blue-200 rounded flex items-center justify-center">
<text class="text-xs">p-4</text>
</view>
<view class="p-6 bg-blue-300 rounded flex items-center justify-center">
<text class="text-xs">p-6</text>
</view>
<view class="p-8 bg-blue-400 rounded flex items-center justify-center">
<text class="text-xs">p-8</text>
</view>
</view>
<view class="mt-4 flex flex-wrap gap-4 items-center">
<view class="m-2 bg-green-100 rounded flex items-center justify-center">
<text class="text-xs">m-2</text>
</view>
<view class="m-4 bg-green-200 rounded flex items-center justify-center">
<text class="text-xs">m-4</text>
</view>
<view class="m-6 bg-green-300 rounded flex items-center justify-center">
<text class="text-xs">m-6</text>
</view>
</view>
</view>
<!-- 文字样式 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">文字样式</text>
<view class="space-y-2">
<text class="text-xs text-gray-600 block">text-xs - 超小文字 (12px)</text>
<text class="text-sm text-gray-600 block">text-sm - 小文字 (14px)</text>
<text class="text-base text-gray-700 block">text-base - 基础文字 (16px)</text>
<text class="text-lg text-gray-800 block">text-lg - 大文字 (18px)</text>
<text class="text-xl text-gray-900 font-bold block">text-xl - 超大文字 (20px)</text>
<text class="text-2xl text-blue-600 font-bold block">text-2xl - 标题文字 (24px)</text>
<text class="text-3xl text-purple-600 font-bold block">text-3xl - 大标题 (30px)</text>
</view>
<view class="mt-4 space-y-2">
<text class="font-thin text-gray-700 block">font-thin - 细体</text>
<text class="font-normal text-gray-700 block">font-normal - 正常</text>
<text class="font-medium text-gray-700 block">font-medium - 中等</text>
<text class="font-semibold text-gray-700 block">font-semibold - 半粗</text>
<text class="font-bold text-gray-700 block">font-bold - 粗体</text>
</view>
</view>
<!-- 文字样式 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">文字样式</text>
<view class="space-y-2">
<text class="text-xs text-gray-600 block">text-xs - 超小文字 (12px)</text>
<text class="text-sm text-gray-600 block">text-sm - 小文字 (14px)</text>
<text class="text-base text-gray-700 block">text-base - 基础文字 (16px)</text>
<text class="text-lg text-gray-800 block">text-lg - 大文字 (18px)</text>
<text class="text-xl text-gray-900 font-bold block">text-xl - 超大文字 (20px)</text>
<text class="text-2xl text-blue-600 font-bold block">text-2xl - 标题文字 (24px)</text>
<text class="text-3xl text-purple-600 font-bold block">text-3xl - 大标题 (30px)</text>
</view>
<view class="mt-4 space-y-2">
<text class="font-thin text-gray-700 block">font-thin - 细体</text>
<text class="font-normal text-gray-700 block">font-normal - 正常</text>
<text class="font-medium text-gray-700 block">font-medium - 中等</text>
<text class="font-semibold text-gray-700 block">font-semibold - 半粗</text>
<text class="font-bold text-gray-700 block">font-bold - 粗体</text>
</view>
</view>
<!-- 按钮样式 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text>
<view class="flex flex-wrap gap-3">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600">Primary</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600">Secondary</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">Success</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">Danger</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">Warning</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">Info</button>
</view>
<view class="mt-3 flex flex-wrap gap-3">
<button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600">Small</button>
<button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">Large</button>
</view>
</view>
<!-- 按钮样式 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text>
<view class="flex flex-wrap gap-3">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600">
Primary
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600">
Secondary
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">
Success
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">
Danger
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">
Warning
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">
Info
</button>
</view>
<view class="mt-3 flex flex-wrap gap-3">
<button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600">
Small
</button>
<button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">
Large
</button>
</view>
</view>
<!-- 卡片组件 -->
<view class="bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm">
<view class="px-4 py-3 bg-gray-50 border-b border-gray-200">
<text class="text-lg font-semibold text-gray-800">卡片组件</text>
</view>
<view class="px-4 py-4">
<text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text>
</view>
<view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end">
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600">操作</button>
</view>
</view>
<!-- 卡片组件 -->
<view class="bg-white border border-gray-200 rounded-lg overflow-hidden shadow-sm">
<view class="px-4 py-3 bg-gray-50 border-b border-gray-200">
<text class="text-lg font-semibold text-gray-800">卡片组件</text>
</view>
<view class="px-4 py-4">
<text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text>
</view>
<view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end">
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600">
操作
</button>
</view>
</view>
<!-- Flexbox 布局 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">Flexbox 布局</text>
<view class="flex gap-2 mb-3">
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">1</text>
</view>
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">2</text>
</view>
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">3</text>
</view>
</view>
<view class="flex justify-between gap-2 mb-3">
<view class="flex-1 bg-green-100 py-3 rounded flex items-center justify-center">
<text class="text-green-800 font-medium">Left</text>
</view>
<view class="flex-1 bg-green-100 py-3 rounded flex items-center justify-center">
<text class="text-green-800 font-medium">Right</text>
</view>
</view>
<view class="flex justify-center gap-2">
<view class="px-6 bg-purple-100 py-3 rounded flex items-center justify-center">
<text class="text-purple-800 font-medium">Center</text>
</view>
</view>
<view class="flex items-center gap-2 mt-3">
<view class="w-12 h-12 bg-red-100 rounded flex items-center justify-center">
<text>Top</text>
</view>
<view class="flex-1 bg-red-100 rounded py-3 flex items-center justify-center">
<text>Middle</text>
</view>
<view class="w-12 h-12 bg-red-100 rounded flex items-center justify-center">
<text>Bottom</text>
</view>
</view>
</view>
<!-- Flexbox 布局 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">Flexbox 布局</text>
<view class="flex gap-2 mb-3">
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">1</text>
</view>
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">2</text>
</view>
<view class="flex-1 bg-blue-100 py-3 rounded flex items-center justify-center">
<text class="text-blue-800 font-medium">3</text>
</view>
</view>
<view class="flex justify-between gap-2 mb-3">
<view class="flex-1 bg-green-100 py-3 rounded flex items-center justify-center">
<text class="text-green-800 font-medium">Left</text>
</view>
<view class="flex-1 bg-green-100 py-3 rounded flex items-center justify-center">
<text class="text-green-800 font-medium">Right</text>
</view>
</view>
<view class="flex justify-center gap-2">
<view class="px-6 bg-purple-100 py-3 rounded flex items-center justify-center">
<text class="text-purple-800 font-medium">Center</text>
</view>
</view>
<view class="flex items-center gap-2 mt-3">
<view class="w-12 h-12 bg-red-100 rounded flex items-center justify-center">
<text>Top</text>
</view>
<view class="flex-1 bg-red-100 rounded py-3 flex items-center justify-center">
<text>Middle</text>
</view>
<view class="w-12 h-12 bg-red-100 rounded flex items-center justify-center">
<text>Bottom</text>
</view>
</view>
</view>
<!-- Grid 布局 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">Grid 布局</text>
<view class="grid grid-cols-2 gap-3 mb-3">
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">1</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">2</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">3</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">4</text>
</view>
</view>
<view class="grid grid-cols-3 gap-2">
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">A</text>
</view>
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">B</text>
</view>
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">C</text>
</view>
</view>
</view>
<!-- Grid 布局 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">Grid 布局</text>
<view class="grid grid-cols-2 gap-3 mb-3">
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">1</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">2</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">3</text>
</view>
<view class="bg-indigo-100 py-4 rounded flex items-center justify-center">
<text class="text-indigo-800">4</text>
</view>
</view>
<view class="grid grid-cols-3 gap-2">
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">A</text>
</view>
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">B</text>
</view>
<view class="bg-teal-100 py-3 rounded flex items-center justify-center">
<text class="text-teal-800 text-xs">C</text>
</view>
</view>
</view>
<!-- 边框和圆角 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">边框和圆角</text>
<view class="flex flex-wrap gap-3">
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-none">
<text class="text-xs">无圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded">
<text class="text-xs">小圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-lg">
<text class="text-xs">大圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-xl">
<text class="text-xs">超大圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-full">
<text class="text-xs">圆形</text>
</view>
</view>
<view class="mt-4 flex flex-wrap gap-3">
<view class="px-4 py-2 border-2 border-blue-500 rounded">border-2</view>
<view class="px-4 py-2 border-4 border-green-500 rounded">border-4</view>
<view class="px-4 py-2 border-l-4 border-purple-500 rounded">border-l-4</view>
<view class="px-4 py-2 border-t-4 border-red-500 rounded">border-t-4</view>
</view>
</view>
<!-- 边框和圆角 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">边框和圆角</text>
<view class="flex flex-wrap gap-3">
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-none">
<text class="text-xs">无圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded">
<text class="text-xs">小圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-lg">
<text class="text-xs">大圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-xl">
<text class="text-xs">超大圆角</text>
</view>
<view class="w-20 h-20 flex items-center justify-center bg-gray-50 border border-gray-300 rounded-full">
<text class="text-xs">圆形</text>
</view>
</view>
<view class="mt-4 flex flex-wrap gap-3">
<view class="px-4 py-2 border-2 border-blue-500 rounded">
border-2
</view>
<view class="px-4 py-2 border-4 border-green-500 rounded">
border-4
</view>
<view class="px-4 py-2 border-l-4 border-purple-500 rounded">
border-l-4
</view>
<view class="px-4 py-2 border-t-4 border-red-500 rounded">
border-t-4
</view>
</view>
</view>
<!-- 阴影效果 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">阴影效果</text>
<view class="flex flex-wrap gap-4">
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-sm">
<text class="text-xs">shadow-sm</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow">
<text class="text-xs">shadow</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-md">
<text class="text-xs">shadow-md</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-lg">
<text class="text-xs">shadow-lg</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-xl">
<text class="text-xs">shadow-xl</text>
</view>
</view>
</view>
<!-- 阴影效果 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">阴影效果</text>
<view class="flex flex-wrap gap-4">
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-sm">
<text class="text-xs">shadow-sm</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow">
<text class="text-xs">shadow</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-md">
<text class="text-xs">shadow-md</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-lg">
<text class="text-xs">shadow-lg</text>
</view>
<view class="w-24 h-24 bg-white flex items-center justify-center rounded shadow-xl">
<text class="text-xs">shadow-xl</text>
</view>
</view>
</view>
<!-- 背景渐变 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">背景渐变</text>
<view class="space-y-3">
<!-- #ifdef APP -->
<view class="bg-blue-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<view class="bg-green-400 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<view class="bg-pink-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-blue-500 to-purple-600</text>
</view>
<view class="bg-gradient-to-r from-green-400 to-blue-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-green-400 to-blue-500</text>
</view>
<view class="bg-gradient-to-r from-pink-500 to-yellow-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-pink-500 to-yellow-500</text>
</view>
<!-- #endif -->
</view>
</view>
<!-- 背景渐变 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">背景渐变</text>
<view class="space-y-3">
<!-- #ifdef APP -->
<view class="bg-blue-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<view class="bg-green-400 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<view class="bg-pink-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">纯色背景 (App 端不支持渐变)</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-blue-500 to-purple-600</text>
</view>
<view class="bg-gradient-to-r from-green-400 to-blue-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-green-400 to-blue-500</text>
</view>
<view class="bg-gradient-to-r from-pink-500 to-yellow-500 rounded-lg p-4">
<text class="text-white font-medium block text-center">from-pink-500 to-yellow-500</text>
</view>
<!-- #endif -->
</view>
</view>
<!-- 定位 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">定位示例</text>
<view class="relative h-32 bg-gray-100 rounded">
<view class="absolute top-2 left-2 px-3 py-1 bg-blue-500 rounded flex items-center justify-center">
<text class="text-white text-xs">top-left</text>
</view>
<view class="absolute top-2 right-2 px-3 py-1 bg-green-500 rounded flex items-center justify-center">
<text class="text-white text-xs">top-right</text>
</view>
<view class="absolute bottom-2 left-2 px-3 py-1 bg-red-500 rounded flex items-center justify-center">
<text class="text-white text-xs">bottom-left</text>
</view>
<view class="absolute bottom-2 right-2 px-3 py-1 bg-purple-500 rounded flex items-center justify-center">
<text class="text-white text-xs">bottom-right</text>
</view>
<view class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 px-3 py-1 bg-yellow-500 rounded flex items-center justify-center">
<text class="text-white text-xs">center</text>
</view>
</view>
</view>
<!-- 定位 -->
<view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">定位示例</text>
<view class="relative h-32 bg-gray-100 rounded">
<view class="absolute top-2 left-2 px-3 py-1 bg-blue-500 rounded flex items-center justify-center">
<text class="text-white text-xs">top-left</text>
</view>
<view class="absolute top-2 right-2 px-3 py-1 bg-green-500 rounded flex items-center justify-center">
<text class="text-white text-xs">top-right</text>
</view>
<view class="absolute bottom-2 left-2 px-3 py-1 bg-red-500 rounded flex items-center justify-center">
<text class="text-white text-xs">bottom-left</text>
</view>
<view class="absolute bottom-2 right-2 px-3 py-1 bg-purple-500 rounded flex items-center justify-center">
<text class="text-white text-xs">bottom-right</text>
</view>
<view class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 px-3 py-1 bg-yellow-500 rounded flex items-center justify-center">
<text class="text-white text-xs">center</text>
</view>
</view>
</view>
<!-- 响应式设计提示 -->
<!-- #ifdef APP -->
<view class="bg-pink-400 rounded-lg p-4 shadow-sm">
<text class="text-white text-center font-medium block mb-2">响应式设计</text>
<text class="text-white text-sm text-center opacity-90 block">weapp-tailwindcss 会自动适配 APP、小程序、H5 等平台</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-pink-400 to-purple-500 rounded-lg p-4 shadow-sm">
<text class="text-white text-center font-medium block mb-2">响应式设计</text>
<text class="text-white text-sm text-center opacity-90 block">weapp-tailwindcss 会自动适配 APP、小程序、H5 等平台</text>
</view>
<!-- #endif -->
<!-- 响应式设计提示 -->
<!-- #ifdef APP -->
<view class="bg-pink-400 rounded-lg p-4 shadow-sm">
<text class="text-white text-center font-medium block mb-2">响应式设计</text>
<text class="text-white text-sm text-center opacity-90 block">weapp-tailwindcss 会自动适配 APP、小程序、H5 等平台</text>
</view>
<!-- #endif -->
<!-- #ifndef APP -->
<view class="bg-gradient-to-r from-pink-400 to-purple-500 rounded-lg p-4 shadow-sm">
<text class="text-white text-center font-medium block mb-2">响应式设计</text>
<text class="text-white text-sm text-center opacity-90 block">weapp-tailwindcss 会自动适配 APP、小程序、H5 等平台</text>
</view>
<!-- #endif -->
<!-- 使用说明 -->
<view class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<text class="text-lg font-semibold text-blue-800 mb-2 block">使用说明</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">1. weapp-tailwindcss 已配置并支持 uni-app x</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">2. 直接使用 Tailwind CSS 类名即可,无需额外配置</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">3. 支持 APP、小程序、H5 多端适配</text>
<text class="text-blue-700 text-sm leading-relaxed block">4. 编译时会自动转换类名为对应平台的样式</text>
</view>
</view>
<!-- #ifdef APP -->
</scroll-view>
<!-- #endif -->
<!-- #ifndef APP -->
</view>
<!-- #endif -->
<!-- 使用说明 -->
<view class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<text class="text-lg font-semibold text-blue-800 mb-2 block">使用说明</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">1. weapp-tailwindcss 已配置并支持 uni-app x</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">2. 直接使用 Tailwind CSS 类名即可,无需额外配置</text>
<text class="text-blue-700 text-sm leading-relaxed block mb-2">3. 支持 APP、小程序、H5 多端适配</text>
<text class="text-blue-700 text-sm leading-relaxed block">4. 编译时会自动转换类名为对应平台的样式</text>
</view>
</view>
<!-- #ifdef APP -->
</view>
</scroll-view>
<!-- #endif -->
<!-- #ifndef APP -->
</view>
<!-- #endif -->
</template>
<script lang="ts" setup>
......
<template>
<scroll-view style="flex: 1" class="flex flex-col bg-indigo-500">
<view class="flex flex-col">
<view class="flex flex-col">
<view class="flex flex-col px-8 pt-10 pb-8 items-center">
<text class="text-3xl font-bold text-white mb-2">uni-app x 示例</text>
<text class="text-base text-white opacity-90">功能演示与测试</text>
</view>
<scroll-view class="flex flex-col bg-indigo-500" style="flex: 1">
<view class="flex flex-col">
<view class="flex flex-col">
<view class="flex flex-col px-8 pt-10 pb-8 items-center">
<text class="text-3xl font-bold text-white mb-2">uni-app x 示例</text>
<text class="text-base text-white opacity-90">功能演示与测试</text>
</view>
<view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl">
<view
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }"
@touchstart="handleTouchStart(item.path)"
@touchend="pressedCard = ''"
@tap="toPath(item)"
v-for="item in data"
:key="item.label + item.path"
>
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center">
<view
class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4"
>
<text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view>
<text class="text-lg font-semibold text-gray-800">
{{ item.label }}
</text>
</view>
<view
class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
style="margin-left: auto"
>
<text class="text-lg text-white font-bold">→</text>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
<view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl">
<view v-for="item in data"
:key="item.label + item.path"
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }"
@tap="toPath(item)"
@touchend="pressedCard = ''"
@touchstart="handleTouchStart(item.path)">
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center">
<view class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4">
<text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view>
<text class="text-lg font-semibold text-gray-800">
{{ item.label }}
</text>
</view>
<view class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
style="margin-left: auto">
<text class="text-lg text-white font-bold">→</text>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
......@@ -48,12 +42,12 @@ import { get } from "@/utils/common.uts";
// import { router } from "@/utils/router.uts";
type Item = {
label: string;
icon?: string;
path?: string;
children?: Item[];
disabled?: boolean;
hidden?: boolean;
children?: Item[];
icon?: string;
label: string;
path?: string;
};
const data = computed<Item[]>(() => {
......@@ -134,8 +128,8 @@ const toPath = (item: Item) => {
// 使用索引访问属性,避免 error18
// NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问
let errMsg = "未知错误";
let errCode: number | null = null;
let errSubject: string | null = null;
let errCode: null | number = null;
let errSubject: null | string = null;
// 尝试使用 UTSJSONObject 转换
try {
......@@ -154,7 +148,7 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string;
}
} catch (e: any) {
} catch {
// 如果转换失败,尝试使用 JSON 序列化/反序列化
try {
const jsonStr = JSON.stringify(err);
......@@ -172,8 +166,8 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string;
}
} catch (e2: any) {
console.error("无法解析错误对象:", e2);
} catch (error: any) {
console.error("无法解析错误对象:", error);
}
}
......
const path = require("node:path");
const { r } = require("./shared");
const path = require("path");
// 确保能找到 tailwindcss-rem2px-preset 模块
// 使用 resolve 来查找模块路径,支持不同的工作目录
......
......@@ -2,19 +2,19 @@
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
"ignoreDeprecations": "5.0",
"verbatimModuleSyntax": true,
"experimentalDecorators": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"noImplicitAny": false,
"types": ["@dcloudio/types", "vue"],
"lib": ["esnext", "dom"],
"outDir": "esbuild",
"experimentalDecorators": true,
"paths": {
"@/*": ["./src/*"],
"$/*": ["./uni_modules/*"]
}
},
"resolveJsonModule": true,
"types": ["@dcloudio/types", "vue"],
"noImplicitAny": false,
"outDir": "esbuild",
"sourceMap": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"vueCompilerOptions": {
"extensions": [".vue", ".uvue"]
......
export type UserInfo = {
unionid: string; // 用户唯一id
id: number; // 用户id
nickName: string; // 昵称
avatarUrl?: string; // 头像
phone: string; // 手机号
gender: number; // 性别
status: number; // 状态
birthday?: string; // 生日
city?: string; // 城市
createTime: string; // 创建时间
description?: string; // 描述
district?: string; // 区县
gender: number; // 性别
id: number; // 用户id
loginType: number; // 登录类型
nickName: string; // 昵称
phone: string; // 手机号
province?: string; // 省份
city?: string; // 城市
district?: string; // 区县
birthday?: string; // 生日
createTime: string; // 创建时间
status: number; // 状态
unionid: string; // 用户唯一id
updateTime: string; // 更新时间
};
export type PushAnimationType =
| "auto"
| "fade-in"
| "none"
| "slide-in-right"
| "pop-in"
| "slide-in-bottom"
| "slide-in-left"
| "slide-in-right"
| "slide-in-top"
| "slide-in-bottom"
| "fade-in"
| "zoom-out"
| "zoom-fade-out"
| "pop-in";
| "zoom-out";
export type BackAnimationType =
| "auto"
| "fade-out"
| "none"
| "slide-out-right"
| "pop-out"
| "slide-out-bottom"
| "slide-out-left"
| "slide-out-right"
| "slide-out-top"
| "slide-out-bottom"
| "fade-out"
| "zoom-in"
| "zoom-fade-in"
| "pop-out";
| "zoom-in";
export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab";
export type BackOptions = {
delta?: number;
animationType?: BackAnimationType;
animationDuration?: number;
success?: (result: any) => void;
fail?: (result: any) => void;
animationType?: BackAnimationType;
complete?: (result: any) => void;
delta?: number;
fail?: (result: any) => void;
success?: (result: any) => void;
};
export type PushOptions = {
path: string;
mode?: PushMode;
animationDuration?: number;
animationType?: PushAnimationType;
complete?: (result: any) => void;
events?: any;
query?: UTSJSONObject;
fail?: (result: any) => void;
isAuth?: boolean;
mode?: PushMode;
params?: UTSJSONObject;
animationType?: PushAnimationType;
animationDuration?: number;
path: string;
query?: UTSJSONObject;
success?: (result: any) => void;
fail?: (result: any) => void;
complete?: (result: any) => void;
};
export type PageInstance = {
path: string;
vm: any;
style?: UTSJSONObject;
query: UTSJSONObject;
exposed: any;
isCustomNavbar: boolean;
meta?: UTSJSONObject;
path: string;
query: UTSJSONObject;
style?: UTSJSONObject;
vm: any;
};
declare module "@dcloudio/vite-plugin-uni";
declare type Theme = "light" | "dark";
declare type Theme = "dark" | "light";
declare interface Uni {
rpx2px(px: number): number;
......@@ -16,28 +16,28 @@ declare interface Uni {
}
declare interface JSON {
parseObject<T>(text: string): T | null;
parseObject<T>(text: string): null | T;
}
declare type UTSJSONObject = {
[key: string]: any;
parse?<T>(): T | null;
get?(key: string): any | null;
set?(key: string, value: any | null): void;
getAny?(key: string): any | null;
getAny?(key: string, def: any): any;
getArray?<T>(key: string): null | T[];
getArray?<T>(key: string, def: T[]): T[];
getArray?(key: string): any[] | null;
getArray?(key: string, def: any[]): any[];
getBoolean?(key: string): boolean | null;
getBoolean?(key: string, def: any): boolean;
getNumber?(key: string): number | null;
getJSON?(key: string): null | UTSJSONObject;
getJSON?(key: string, def: any): UTSJSONObject;
getNumber?(key: string): null | number;
getNumber?(key: string, def: any): number;
getString?(key: string): string | null;
getString?(key: string): null | string;
getString?(key: string, def: any): string;
getJSON?(key: string): UTSJSONObject | null;
getJSON?(key: string, def: any): UTSJSONObject;
getArray?<T>(key: string): T[] | null;
getArray?<T>(key: string, def: T[]): T[];
getArray?(key: string): any[] | null;
getArray?(key: string, def: any[]): any[];
parse?<T>(): null | T;
set?(key: string, value: any | null): void;
toMap?(): Map<string, any>;
};
......@@ -49,14 +49,14 @@ declare interface ChooseImageTempFile {
}
declare type RequestMethod =
| "OPTIONS"
| "CONNECT"
| "DELETE"
| "GET"
| "HEAD"
| "OPTIONS"
| "POST"
| "PUT"
| "DELETE"
| "TRACE"
| "CONNECT";
| "TRACE";
declare interface DOMRect {
x: number;
......@@ -82,33 +82,33 @@ declare interface UniElement {
style: CSSStyleDeclaration;
classList: string[];
takeSnapshot(options: {
success?: (res: { tempFilePath: string }) => void;
fail?: (err: { errCode: number; errMsg: string }) => void;
success?: (res: { tempFilePath: string }) => void;
}): void;
getBoundingClientRectAsync(): Promise<DOMRect>;
getDrawableContext(): DrawableContext;
animate(
keyframes: UniAnimationKeyframe | UniAnimationKeyframe[],
options?:
| number
| {
delay?: number;
direction?: "normal" | "reverse" | "alternate" | "alternate-reverse";
direction?: "alternate" | "alternate-reverse" | "normal" | "reverse";
duration?: number;
easing?:
| "cubic-bezier"
| "ease"
| "ease-in"
| "ease-out"
| "ease-in-out"
| "linear"
| "cubic-bezier";
fill?: "backwards" | "forwards" | "both" | "none";
| "ease-out"
| "linear";
fill?: "backwards" | "both" | "forwards" | "none";
iterations?: number;
}
| number
): {
): null | {
id: string;
playState: "running" | "paused" | "finished" | "idle";
} | null;
playState: "finished" | "idle" | "paused" | "running";
};
}
declare interface CanvasContext extends HTMLCanvasElement {
......
......@@ -13,7 +13,7 @@ export function isArray(value: any): boolean {
* @example isObject([]) // false
*/
export function isObject(value: any): boolean {
return typeof value == "object" && !Array.isArray(value) && !isNull(value);
return typeof value === "object" && !Array.isArray(value) && !isNull(value);
}
/**
......@@ -22,7 +22,7 @@ export function isObject(value: any): boolean {
* @example isString(123) // false
*/
export function isString(value: any): boolean {
return typeof value == "string";
return typeof value === "string";
}
/**
......@@ -31,7 +31,7 @@ export function isString(value: any): boolean {
* @example isNumber('123') // false
*/
export function isNumber(value: any): boolean {
return typeof value == "number" && !isNaN(value);
return typeof value === "number" && !isNaN(value);
}
/**
......@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean {
* @example isBoolean(1) // false
*/
export function isBoolean(value: any): boolean {
return typeof value == "boolean";
return typeof value === "boolean";
}
/**
......@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean {
* @example isFunction({}) // false
*/
export function isFunction(value: any): boolean {
return typeof value == "function";
return typeof value === "function";
}
/**
......@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean {
*/
export function isEmpty(value: any): boolean {
if (isArray(value)) {
return (value as any[]).length == 0;
return (value as any[]).length === 0;
}
if (isString(value)) {
......@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean {
}
if (isObject(value)) {
return keys(value).length == 0;
return keys(value).length === 0;
}
return false;
......@@ -103,7 +103,7 @@ export function keys(value: any): string[] {
* @example first([1, 2, 3]) // 1
* @example first([]) // null
*/
export function first<T>(array: T[]): T | null {
export function first<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[0] : null;
}
......@@ -112,7 +112,7 @@ export function first<T>(array: T[]): T | null {
* @example last([1, 2, 3]) // 3
* @example last([]) // null
*/
export function last<T>(array: T[]): T | null {
export function last<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[array.length - 1] : null;
}
......@@ -179,8 +179,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U):
if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) {
result.push(iteratee(array[i], i));
for (const [i, element] of array.entries()) {
result.push(iteratee(element, i));
}
return result;
......@@ -198,8 +198,8 @@ export function reduce<T, U>(
if (!isArray(array)) return initialValue;
let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) {
accumulator = iteratee(accumulator, array[i], i);
for (const [i, element] of array.entries()) {
accumulator = iteratee(accumulator, element, i);
}
return accumulator;
......@@ -212,8 +212,8 @@ export function reduce<T, U>(
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
return false;
}
}
......@@ -228,8 +228,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo
export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return true;
}
}
......@@ -247,8 +247,7 @@ export function uniq<T>(array: T[]): T[] {
const result: T[] = [];
const seen = new Map<T, boolean>();
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
const key = item;
if (!seen.has(item)) {
seen.set(key, true);
......@@ -268,8 +267,7 @@ export function flatten(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...(item as any[]));
} else {
......@@ -289,8 +287,7 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...flattenDeep(item as any[]));
} else {
......@@ -310,11 +307,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array];
return result.sort((a, b) => {
if (typeof a == "number" && typeof b == "number") {
if (typeof a === "number" && typeof b === "number") {
return order == "asc" ? a - b : b - a;
}
if (typeof a == "string" && typeof b == "string") {
if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
}
......@@ -354,15 +351,14 @@ export function groupBy<T>(array: T[], key: string) {
const result = {};
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
let value = get(item as any, key)!;
if (typeof value == "number") {
if (typeof value === "number") {
value = value.toString();
}
if (typeof value == "string") {
if (typeof value === "string") {
if (!isArray(result[value])) {
result[value] = new Array<T>();
}
......@@ -388,7 +384,7 @@ export function assign(...items: any[]) {
* @example nth([1, 2, 3], 1) // 2
* @example nth([1, 2, 3], -1) // 3
*/
export function nth<T>(array: T[], index: number): T | null {
export function nth<T>(array: T[], index: number): null | T {
if (index >= 0) {
return array[index];
}
......@@ -415,9 +411,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = [];
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
result.push(array[i]);
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
result.push(element);
}
}
......@@ -432,9 +428,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
if (isArray(data)) {
const array = data as T[];
for (let i = 0; i < array.length; i++) {
if (array[i] != null) {
iteratee(array[i], i);
for (const [i, element] of array.entries()) {
if (element != null) {
iteratee(element, i);
}
}
}
......@@ -444,12 +440,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
* 查找数组中第一个满足条件的元素
* @example find([1, 2, 3, 4], x => x > 2) // 3
*/
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): T | null {
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): null | T {
if (!isArray(array)) return null;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return array[i];
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return element;
}
}
return null;
......@@ -462,8 +458,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool
export function forInObject(data: any, iteratee: (value: any, key: string) => void): void {
if (isObject(data)) {
const objKeys = keys(data);
for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i];
for (const key of objKeys) {
iteratee(get(data, key)!, key);
}
}
......@@ -585,9 +580,9 @@ export function random(min: number, max: number): number {
*/
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5
let bytes = window.atob(data.split(",")[1]);
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
const bytes = window.atob(data.split(",")[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
......
import { isArray, parse } from "../utils";
type Page = {
meta?: UTSJSONObject;
path: string;
style?: UTSJSONObject;
meta?: UTSJSONObject;
};
type SubPackage = {
root: string;
pages: Page[];
root: string;
};
export type TabBarItem = {
text?: string;
pagePath: string;
iconPath?: string;
pagePath: string;
selectedIconPath?: string;
text?: string;
visible?: boolean;
};
export type TabBar = {
custom?: boolean;
color?: string;
selectedColor?: string;
backgroundColor?: string;
borderStyle?: string;
backgroundImage?: string;
backgroundRepeat?: "no-repeat" | "repeat" | "repeat-x" | "repeat-y";
blurEffect?: "dark" | "extralight" | "light" | "none";
list?: TabBarItem[];
position?: "top" | "bottom";
borderStyle?: string;
color?: string;
custom?: boolean;
fontSize?: string;
iconWidth?: string;
spacing?: string;
height?: string;
backgroundImage?: string;
backgroundRepeat?: "repeat" | "repeat-x" | "repeat-y" | "no-repeat";
iconWidth?: string;
list?: TabBarItem[];
position?: "bottom" | "top";
redDotColor?: string;
selectedColor?: string;
spacing?: string;
};
export type Ctx = {
appid: string;
color: UTSJSONObject;
globalStyle: UTSJSONObject;
pages: Page[];
uniIdRouter: UTSJSONObject;
theme: UTSJSONObject;
tabBar: TabBar;
subPackages: SubPackage[];
SAFE_CHAR_MAP_LOCALE: string[][];
color: UTSJSONObject;
subPackages: SubPackage[];
tabBar: TabBar;
theme: UTSJSONObject;
uniIdRouter: UTSJSONObject;
};
// 初始化 ctx 对象,不可修改!!
......@@ -64,7 +64,7 @@ if (isArray(ctx.subPackages)) {
ctx.subPackages.forEach((a) => {
a.pages.forEach((b) => {
PAGES.push({
path: a.root + "/" + b.path, // 拼接子包根路径和页面路径
path: `${a.root }/${ b.path}`, // 拼接子包根路径和页面路径
style: b.style,
meta: b.meta
});
......@@ -75,7 +75,7 @@ if (isArray(ctx.subPackages)) {
// 确保每个页面路径都以 "/" 开头,符合 uni-app x 规范
PAGES.forEach((e) => {
if (!e.path.startsWith("/")) {
e.path = "/" + e.path;
e.path = `/${ e.path}`;
}
});
......
export * from "./storage.uts";
export * from "./common.uts";
export * from "./parse.uts";
export * from "./storage.uts";
......@@ -9,11 +9,11 @@ import LocalStore from "./local-store";
// ===== 1. 定义数据 Schema =====
type UserSchema = {
name: string;
age: number;
createdAt: number;
email: string;
name: string;
status: "active" | "inactive";
createdAt: number;
updatedAt: number;
};
......@@ -199,10 +199,10 @@ try {
// 场景1:用户收藏管理
type FavoriteSchema = {
userId: string;
itemId: string;
itemType: "article" | "video" | "product";
createdAt: number;
itemId: string;
itemType: "article" | "product" | "video";
userId: string;
};
const favoriteStore = new LocalStore<FavoriteSchema>("favorite", {
......@@ -230,11 +230,11 @@ const userFavorites = favoriteStore.find({
// 场景2:购物车管理
type CartItemSchema = {
addedAt: number;
price: number;
productId: string;
productName: string;
price: number;
quantity: number;
addedAt: number;
};
const cartStore = new LocalStore<CartItemSchema>("cart", {
......@@ -262,6 +262,6 @@ if (cartItems.length > 0) {
// 计算购物车总价
let totalPrice = 0;
for (let i = 0; i < cartItems.length; i++) {
totalPrice += cartItems[i].price * cartItems[i].quantity;
for (const cartItem of cartItems) {
totalPrice += cartItem.price * cartItem.quantity;
}
......@@ -35,7 +35,7 @@
* ```
*/
import { isNull, isObject, isArray, keys, get, has, set } from "./common";
import { get, has, isArray, isNull, keys, set } from "./common";
// 更新数据类型
// UTS 不支持 Partial<T>,使用 any 类型,运行时检查
......@@ -44,15 +44,15 @@ type UpdateData<T> = any;
// 查询操作符类型
type QueryOperator =
| "$eq"
| "$ne"
| "$exists"
| "$gt"
| "$gte"
| "$lt"
| "$lte"
| "$in"
| "$nin"
| "$like"
| "$exists";
| "$lt"
| "$lte"
| "$ne"
| "$nin";
// 字段查询操作符类型(UTS 不支持内联对象字面量类型和条件类型,需要先定义)
// 注意:由于 UTS 不支持条件类型,这里使用 number 和 string 类型
......@@ -61,15 +61,15 @@ type QueryOperator =
// 运行时会在 matchCondition 方法中进行类型检查
type FieldQueryOperator<FieldType> = {
$eq?: FieldType;
$ne?: FieldType;
$exists?: boolean;
$gt?: number; // 比较操作符用于数字类型
$gte?: number;
$in?: FieldType[];
$like?: string; // like 操作符用于字符串类型
$lt?: number;
$lte?: number;
$in?: FieldType[];
$ne?: FieldType;
$nin?: FieldType[];
$like?: string; // like 操作符用于字符串类型
$exists?: boolean;
};
// 查询条件类型
......@@ -93,16 +93,16 @@ type SortOption<T> = {
// 查询选项
type FindOptions<T> = {
where?: QueryCondition<T>;
sort?: SortOption<T>[];
limit?: number;
skip?: number;
sort?: SortOption<T>[];
where?: QueryCondition<T>;
};
// 统计信息类型
type Stats = {
total: number;
size: number;
total: number;
};
/**
......@@ -110,9 +110,6 @@ type Stats = {
*/
// UTS 不支持 Record<string, any>,使用 any 约束
class LocalStore<T extends any> {
// 存储前缀
private prefix: string;
// Schema 默认值
private defaults: T;
......@@ -122,6 +119,9 @@ class LocalStore<T extends any> {
// 索引存储前缀
private indexPrefix: string;
// 存储前缀
private prefix: string;
/**
* 构造函数
* @param name 存储名称(作为命名空间前缀)
......@@ -135,180 +135,421 @@ class LocalStore<T extends any> {
}
/**
* 生成唯一 ID
* 使用时间戳 + 随机字符串,确保唯一性
* 清空所有记录
*/
private generateId(): string {
return `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
clear(): void {
const ids = this.getIds();
for (const id of ids) {
const key = this.getRecordKey(id);
uni.removeStorageSync(key);
}
this.saveIds([]);
}
/**
* 获取记录的存储 key
* 统计记录数量
*/
private getRecordKey(id: string | number): string {
// UTS 不支持 String() 构造函数,使用 toString() 或模板字符串
const idStr = typeof id == "string" ? id : id.toString();
return `${this.prefix}:${idStr}`;
count(where?: QueryCondition<T>): number {
if (where == null) {
return this.getIds().length;
}
return this.find({ where }).length;
}
/**
* 获取索引的存储 key
* 创建索引(用于快速查找)
* @param field 要建立索引的字段名
*/
private getIndexKey(field: string, value: any): string {
const valueStr = typeof value == "string" ? value : JSON.stringify(value);
return `${this.indexPrefix}:${field}:${valueStr}`;
// UTS 不支持 keyof T,使用 string 类型
createIndex(field: string): void {
// 获取所有记录
const records = this.findAll();
// 清空该字段的旧索引
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
// 建立新索引:字段值 -> ID 列表
// UTS 不支持 Record 类型,使用 any 类型
const index: any = {};
for (const record of records) {
// UTS 对象属性访问需要使用 get 函数
const value = get(record, field);
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";
// 使用 set 和 get 维护索引,避免直接使用下标访问
// 显式指定空数组类型为 any[]
const emptyArray: any[] = [];
if (!has(index, valueKey)) {
set(index, valueKey, emptyArray);
}
let idList = get(index, valueKey) as any[] | null;
// 确保 idList 不为 null,强制断言为非空数组
if (isNull(idList) || !isArray(idList)) {
idList = [];
}
// 使用非空断言,确保 idList 是数组类型
const idListArray = idList as any[];
const recordAny = record as any;
const idValue = get(recordAny, "id");
// idValue 可能为 null,需要检查后使用类型断言
if (!isNull(idValue)) {
// idListArray 是非空数组,idValue 也不为 null
idListArray.push(idValue as any);
}
set(index, valueKey, idListArray);
}
// 保存索引
uni.setStorageSync(indexKey, index);
}
/**
* 深拷贝对象
* 删除记录
*/
private deepClone(obj: any): any | null {
// UTS 要求返回类型明确包含 null
if (obj == null) {
return null;
delete(id: number | string): boolean {
if (!this.exists(id)) {
return false;
}
if (typeof obj == "object") {
return JSON.parse(JSON.stringify(obj));
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
} catch (error) {
console.error(`[LocalStore] 删除失败:`, error);
return false;
}
return obj;
// 从 ID 列表中移除
this.removeId(id);
return true;
}
/**
* 获取所有记录的 ID 列表
* 批量删除(优化版本,直接操作 ID 列表)
* @param ids 要删除的 ID 数组
*/
private getIds(): (string | number)[] {
const ids = uni.getStorageSync(this.idsKey);
if (isNull(ids) || !isArray(ids)) {
return [];
deleteByIds(ids: (number | string)[]): number {
if (ids.length === 0) {
return 0;
}
return ids as (string | number)[];
}
/**
* 保存 ID 列表
*/
private saveIds(ids: (string | number)[]): void {
uni.setStorageSync(this.idsKey, ids);
}
let count = 0;
const allIds = this.getIds();
/**
* 添加 ID 到列表
*/
private addId(id: string | number): void {
const ids = this.getIds();
if (!ids.includes(id)) {
ids.push(id);
this.saveIds(ids);
// 批量删除存储
for (const id of ids) {
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
count++;
} catch (error) {
console.error(`[LocalStore] 删除失败 ID=${id}:`, error);
}
}
}
/**
* 从列表中移除 ID
*/
private removeId(id: string | number): void {
const ids = this.getIds();
const index = ids.indexOf(id);
if (index != -1) {
ids.splice(index, 1);
this.saveIds(ids);
// 批量更新 ID 列表(一次性操作)
const remainingIds: (number | string)[] = [];
for (const allId of allIds) {
if (!ids.includes(allId)) {
remainingIds.push(allId);
}
}
this.saveIds(remainingIds);
return count;
}
/**
* 验证数据是否符合 schema
* 批量删除
*/
// UTS 不支持 Partial<T>,使用 any 类型
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
private validateData(data: any): boolean {
const dataKeys = keys(data);
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
if (!has(this.defaults, key)) {
console.warn(`[LocalStore] 未知字段 "${key}" 在 store "${this.prefix}" 中`);
return false;
deleteMany(where: QueryCondition<T>): number {
const records = this.find({ where });
if (records.length === 0) {
return 0;
}
let count = 0;
for (const record of records) {
const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as null | number | string;
if (record != null && !isNull(idValue) && this.delete(idValue as number | string)) {
count++;
}
}
return true;
return count;
}
/**
* 合并默认值
* 删除索引
*/
// UTS 不支持 Partial<T>,使用 any 类型
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
// UTS 对象属性访问需要使用 UTSJSONObject 方式
private mergeDefaults(data: any): T {
const result = this.deepClone(this.defaults) as T;
const dataKeys = keys(data);
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
if (has(this.defaults, key)) {
// UTS 对象属性访问需要使用 get 和 set 函数
const value = get(data, key);
set(result, key, value);
}
}
return result;
// UTS 不支持 keyof T,使用 string 类型
dropIndex(field: string): void {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
}
/**
* 检查记录是否存在
*/
exists(id: string | number): boolean {
exists(id: number | string): boolean {
const key = this.getRecordKey(id);
const record = uni.getStorageSync(key);
return record != null && record != "";
}
/**
* 获取单条记录
* 查询记录
*/
get(id: string | number): RecordWithId<T> | null {
if (!this.exists(id)) {
return null;
}
const key = this.getRecordKey(id);
const record = uni.getStorageSync(key) as T | null;
find(options?: FindOptions<T>): RecordWithId<T>[] {
const ids = this.getIds();
let results: RecordWithId<T>[] = [];
if (isNull(record)) {
return null;
// 获取所有记录
for (const id of ids) {
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
// 合并默认值,确保所有字段都存在
// record 已经检查过不为 null,使用类型断言
const merged = this.mergeDefaults(record as any);
// UTS 不支持对象展开运算符,需要手动创建对象
const result: any = {};
const mergedKeys = keys(merged);
for (let i = 0; i < mergedKeys.length; i++) {
const key = mergedKeys[i];
const value = get(merged, key);
set(result, key, value);
// 应用查询条件
if (options != null && options.where != null) {
results = results.filter((record) => this.matchCondition(record, options.where!));
}
set(result, "id", id);
return result as RecordWithId<T>;
}
/**
* 插入新记录
* @param idOrData 可以是 ID(string/number),也可以是数据对象(此时自动生成 ID)
* @param data 如果第一个参数是 ID,则此为数据;否则忽略
* @returns 实际使用的 ID
*/
// UTS 不支持 Partial<T>,使用 any 类型
insert(idOrData: string | number | any, data?: any): string | number {
let id: string | number;
let finalData: any;
// 应用排序
if (options != null && options.sort != null && options.sort.length > 0) {
results.sort((a, b) => {
for (let i = 0; i < options.sort!.length; i++) {
const sortOption = options.sort![i];
const field = sortOption.field;
// UTS 对象属性访问需要使用 get 函数,get 返回 any | null
const aValueAny = get(a, field);
const bValueAny = get(b, field);
if (typeof idOrData == "object") {
// 调用方式:store.insert({ name: 'Alice' })
finalData = idOrData;
id = this.generateId();
} else {
// 调用方式:store.insert('user_123', { name: 'Alice' })
id = idOrData;
finalData = data != null ? data : {};
// 如果值为 null,跳过比较(null 值排在最后)
if (isNull(aValueAny) || isNull(bValueAny)) {
if (isNull(aValueAny) && isNull(bValueAny)) {
continue; // 两个都是 null,继续下一个字段
}
// 一个为 null,另一个不为 null,null 排在后面
return isNull(aValueAny) ? 1 : -1;
}
// 确保值不为 null,使用类型断言
const aValue = aValueAny as any;
const bValue = bValueAny as any;
let comparison = 0;
if (typeof aValue === "number" && typeof bValue === "number") {
comparison = aValue - bValue;
} else if (typeof aValue === "string" && typeof bValue === "string") {
// UTS 不支持直接使用 < > 比较字符串,手动实现字符串比较
const aStr = aValue as string;
const bStr = bValue as string;
const aLen = aStr.length;
const bLen = bStr.length;
const minLen = Math.min(aLen, bLen);
// 逐个字符比较(使用字符串索引访问)
for (let j = 0; j < minLen; j++) {
// UTS 字符串索引访问,charCodeAt 返回 Number?,这里断言为 number
const aCharCode = aStr.charCodeAt(j) as number;
const bCharCode = bStr.charCodeAt(j) as number;
if (aCharCode < bCharCode) {
comparison = -1;
break;
} else if (aCharCode > bCharCode) {
comparison = 1;
break;
}
}
// 如果前面的字符都相同,比较长度
if (comparison == 0) {
if (aLen < bLen) {
comparison = -1;
} else if (aLen > bLen) {
comparison = 1;
}
}
}
if (comparison != 0) {
return sortOption.order == "asc" ? comparison : -comparison;
}
}
return 0;
});
}
// 应用 skip
if (options != null && options.skip != null) {
const skipValue = options.skip;
if (skipValue > 0) {
results = results.slice(skipValue);
}
}
// 应用 limit
if (options != null && options.limit != null) {
const limitValue = options.limit;
if (limitValue > 0) {
results = results.slice(0, limitValue);
}
}
return results;
}
/**
* 获取所有记录
*/
findAll(): RecordWithId<T>[] {
// UTS 要求显式传入参数,这里传入空配置对象
const emptyOptions: any = {};
return this.find(emptyOptions as FindOptions<T>);
}
/**
* 根据索引查找记录
* @param field 索引字段
* @param value 字段值
*/
// UTS 不支持 keyof T,使用 string 类型
findByIndex(field: string, value: any): RecordWithId<T>[] {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
// UTS 不支持 Record 类型,使用 any 类型
const index = uni.getStorageSync(indexKey) as any | null;
if (isNull(index)) {
// 索引不存在,使用普通查询
// UTS 不支持计算属性名 [field],需要先创建对象
const whereCondition: any = {};
set(whereCondition, field, value);
return this.find({ where: whereCondition as QueryCondition<T> });
}
// index 已经检查过不为 null,使用类型断言
// UTS 不支持 Record 类型,使用 any 类型
const indexObj = index as any;
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";
// 使用 get 获取 ids,避免下标访问
const idsAny = get(indexObj, valueKey);
if (isNull(idsAny) || !isArray(idsAny)) {
return [];
}
// 确保 ids 是数组类型
const ids = idsAny as any[];
const results: RecordWithId<T>[] = [];
for (const id of ids) {
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
return results;
}
/**
* 查找第一条匹配的记录
*/
findFirst(where?: QueryCondition<T>): null | RecordWithId<T> {
const results = this.find({ where, limit: 1 });
return results.length > 0 ? results[0] : null;
}
/**
* 查找单条记录
*/
findOne(id: number | string): null | RecordWithId<T> {
return this.get(id);
}
/**
* 获取单条记录
*/
get(id: number | string): null | RecordWithId<T> {
if (!this.exists(id)) {
return null;
}
const key = this.getRecordKey(id);
const record = uni.getStorageSync(key) as null | T;
if (isNull(record)) {
return null;
}
// 合并默认值,确保所有字段都存在
// record 已经检查过不为 null,使用类型断言
const merged = this.mergeDefaults(record as any);
// UTS 不支持对象展开运算符,需要手动创建对象
const result: any = {};
const mergedKeys = keys(merged);
for (const key of mergedKeys) {
const value = get(merged, key);
set(result, key, value);
}
set(result, "id", id);
return result as RecordWithId<T>;
}
/**
* 获取存储统计信息
*/
getStats(): Stats {
const ids = this.getIds();
let totalSize = 0;
// 估算存储大小(简单实现)
for (const id of ids) {
const record = this.get(id);
if (record != null) {
const recordStr = JSON.stringify(record);
totalSize += recordStr.length;
}
}
return {
total: ids.length,
size: totalSize
};
}
/**
* 插入新记录
* @param idOrData 可以是 ID(string/number),也可以是数据对象(此时自动生成 ID)
* @param data 如果第一个参数是 ID,则此为数据;否则忽略
* @returns 实际使用的 ID
*/
// UTS 不支持 Partial<T>,使用 any 类型
insert(idOrData: any | number | string, data?: any): number | string {
let id: number | string;
let finalData: any;
if (typeof idOrData === "object") {
// 调用方式:store.insert({ name: 'Alice' })
finalData = idOrData;
id = this.generateId();
} else {
// 调用方式:store.insert('user_123', { name: 'Alice' })
id = idOrData;
finalData = data != null ? data : {};
}
// 验证数据
......@@ -339,9 +580,66 @@ class LocalStore<T extends any> {
}
/**
* 批量插入
* 内部自动分批处理,避免一次性操作过多导致性能问题
* @param items 要插入的数据数组
* @param batchSize 每批处理的条数,默认100条
*/
// UTS 不支持 Partial<T>,使用 any 类型
insertMany(items: any[], batchSize: number = 100): (number | string)[] {
const ids: (number | string)[] = [];
const total = items.length;
// 如果数据量小于批次大小,直接处理
if (total <= batchSize) {
for (const item of items) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(item, null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败:`, error);
}
}
return ids;
}
// 大数据量时,分批处理
const batchCount = Math.ceil(total / batchSize);
for (let batch = 0; batch < batchCount; batch++) {
const start = batch * batchSize;
const end = Math.min(start + batchSize, total);
// 处理当前批次
for (let i = start; i < end; i++) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(items[i], null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败 [${i + 1}/${total}]:`, error);
}
}
}
return ids;
}
/**
* 重建所有索引(在数据迁移后使用)
*/
// UTS 不支持 keyof T,使用 string[] 类型
rebuildIndexes(fields: string[]): void {
for (const field of fields) {
this.createIndex(field);
}
}
/**
* 更新记录(部分更新)
*/
update(id: string | number, updates: UpdateData<T>): boolean {
update(id: number | string, updates: UpdateData<T>): boolean {
if (!this.exists(id)) {
console.warn(`[LocalStore] 记录 "${id}" 不存在`);
return false;
......@@ -366,8 +664,7 @@ class LocalStore<T extends any> {
const updated: any = {};
// 先复制 existing 的所有属性
const existingKeys = keys(existingAny);
for (let i = 0; i < existingKeys.length; i++) {
const key = existingKeys[i];
for (const key of existingKeys) {
if (key != "id") {
// 跳过 id 字段
const value = get(existingAny, key);
......@@ -376,8 +673,7 @@ class LocalStore<T extends any> {
}
// 再复制 updates 的所有属性(覆盖 existing)
const updatesKeys = keys(updates);
for (let i = 0; i < updatesKeys.length; i++) {
const key = updatesKeys[i];
for (const key of updatesKeys) {
const value = get(updates, key);
set(updated, key, value);
}
......@@ -396,61 +692,81 @@ class LocalStore<T extends any> {
}
/**
* 删除记录
* 批量更新
*/
delete(id: string | number): boolean {
if (!this.exists(id)) {
return false;
updateMany(where: QueryCondition<T>, updates: UpdateData<T>): number {
const records = this.find({ where });
let count = 0;
for (const record of records) {
const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as null | number | string;
if (!isNull(idValue) && this.update(idValue as number | string, updates)) {
count++;
}
}
return count;
}
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
} catch (error) {
console.error(`[LocalStore] 删除失败:`, error);
return false;
/**
* 添加 ID 到列表
*/
private addId(id: number | string): void {
const ids = this.getIds();
if (!ids.includes(id)) {
ids.push(id);
this.saveIds(ids);
}
// 从 ID 列表中移除
this.removeId(id);
return true;
}
/**
* 批量删除(优化版本,直接操作 ID 列表)
* @param ids 要删除的 ID 数组
* 深拷贝对象
*/
deleteByIds(ids: (string | number)[]): number {
if (ids.length == 0) {
return 0;
private deepClone(obj: any): any | null {
// UTS 要求返回类型明确包含 null
if (obj == null) {
return null;
}
if (typeof obj === "object") {
return JSON.parse(JSON.stringify(obj));
}
return obj;
}
let count = 0;
const allIds = this.getIds();
/**
* 生成唯一 ID
* 使用时间戳 + 随机字符串,确保唯一性
*/
private generateId(): string {
return `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}
// 批量删除存储
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
count++;
} catch (error) {
console.error(`[LocalStore] 删除失败 ID=${id}:`, error);
}
/**
* 获取所有记录的 ID 列表
*/
private getIds(): (number | string)[] {
const ids = uni.getStorageSync(this.idsKey);
if (isNull(ids) || !isArray(ids)) {
return [];
}
return ids as (number | string)[];
}
// 批量更新 ID 列表(一次性操作)
const remainingIds: (string | number)[] = [];
for (let i = 0; i < allIds.length; i++) {
if (!ids.includes(allIds[i])) {
remainingIds.push(allIds[i]);
}
}
this.saveIds(remainingIds);
/**
* 获取索引的存储 key
*/
private getIndexKey(field: string, value: any): string {
const valueStr = typeof value === "string" ? value : JSON.stringify(value);
return `${this.indexPrefix}:${field}:${valueStr}`;
}
return count;
/**
* 获取记录的存储 key
*/
private getRecordKey(id: number | string): string {
// UTS 不支持 String() 构造函数,使用 toString() 或模板字符串
const idStr = typeof id === "string" ? id : id.toString();
return `${this.prefix}:${idStr}`;
}
/**
......@@ -459,8 +775,7 @@ class LocalStore<T extends any> {
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
private matchCondition(record: RecordWithId<T>, condition: QueryCondition<T>): boolean {
const conditionKeys = keys(condition);
for (let i = 0; i < conditionKeys.length; i++) {
const field = conditionKeys[i];
for (const field of conditionKeys) {
// UTS 对象属性访问需要使用 get 函数
const fieldValue = get(record, field);
const conditionValue = get(condition, field);
......@@ -470,7 +785,7 @@ class LocalStore<T extends any> {
}
// 简单值匹配(等于)
if (typeof conditionValue != "object") {
if (typeof conditionValue !== "object") {
if (fieldValue != conditionValue) {
return false;
}
......@@ -500,7 +815,7 @@ class LocalStore<T extends any> {
// $gt - 大于
if (has(operators, "$gt")) {
const gtValue = get(operators, "$gt") as number;
if (typeof fieldValue != "number") {
if (typeof fieldValue !== "number") {
return false;
}
const numValue = fieldValue as number;
......@@ -512,7 +827,7 @@ class LocalStore<T extends any> {
// $gte - 大于等于
if (has(operators, "$gte")) {
const gteValue = get(operators, "$gte") as number;
if (typeof fieldValue != "number") {
if (typeof fieldValue !== "number") {
return false;
}
const numValue = fieldValue as number;
......@@ -524,7 +839,7 @@ class LocalStore<T extends any> {
// $lt - 小于
if (has(operators, "$lt")) {
const ltValue = get(operators, "$lt") as number;
if (typeof fieldValue != "number") {
if (typeof fieldValue !== "number") {
return false;
}
const numValue = fieldValue as number;
......@@ -536,7 +851,7 @@ class LocalStore<T extends any> {
// $lte - 小于等于
if (has(operators, "$lte")) {
const lteValue = get(operators, "$lte") as number;
if (typeof fieldValue != "number") {
if (typeof fieldValue !== "number") {
return false;
}
const numValue = fieldValue as number;
......@@ -572,10 +887,10 @@ class LocalStore<T extends any> {
// $like - 字符串匹配(简单实现)
if (has(operators, "$like")) {
const likeValue = get(operators, "$like") as string;
if (typeof fieldValue != "string" || typeof likeValue != "string") {
if (typeof fieldValue !== "string" || typeof likeValue !== "string") {
return false;
}
const pattern = likeValue.replace(/%/g, ".*");
const pattern = likeValue.replaceAll("%", ".*");
const regex = new RegExp(`^${pattern}$`);
if (!regex.test(fieldValue)) {
return false;
......@@ -597,385 +912,59 @@ class LocalStore<T extends any> {
}
/**
* 查询记录
*/
find(options?: FindOptions<T>): RecordWithId<T>[] {
const ids = this.getIds();
let results: RecordWithId<T>[] = [];
// 获取所有记录
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
// 应用查询条件
if (options != null && options.where != null) {
results = results.filter((record) => this.matchCondition(record, options.where!));
}
// 应用排序
if (options != null && options.sort != null && options.sort.length > 0) {
results.sort((a, b) => {
for (let i = 0; i < options.sort!.length; i++) {
const sortOption = options.sort![i];
const field = sortOption.field;
// UTS 对象属性访问需要使用 get 函数,get 返回 any | null
const aValueAny = get(a, field);
const bValueAny = get(b, field);
// 如果值为 null,跳过比较(null 值排在最后)
if (isNull(aValueAny) || isNull(bValueAny)) {
if (isNull(aValueAny) && isNull(bValueAny)) {
continue; // 两个都是 null,继续下一个字段
}
// 一个为 null,另一个不为 null,null 排在后面
return isNull(aValueAny) ? 1 : -1;
}
// 确保值不为 null,使用类型断言
const aValue = aValueAny as any;
const bValue = bValueAny as any;
let comparison = 0;
if (typeof aValue == "number" && typeof bValue == "number") {
comparison = aValue - bValue;
} else if (typeof aValue == "string" && typeof bValue == "string") {
// UTS 不支持直接使用 < > 比较字符串,手动实现字符串比较
const aStr = aValue as string;
const bStr = bValue as string;
const aLen = aStr.length;
const bLen = bStr.length;
const minLen = aLen < bLen ? aLen : bLen;
// 逐个字符比较(使用字符串索引访问)
for (let j = 0; j < minLen; j++) {
// UTS 字符串索引访问,charCodeAt 返回 Number?,这里断言为 number
const aCharCode = aStr.charCodeAt(j) as number;
const bCharCode = bStr.charCodeAt(j) as number;
if (aCharCode < bCharCode) {
comparison = -1;
break;
} else if (aCharCode > bCharCode) {
comparison = 1;
break;
}
}
// 如果前面的字符都相同,比较长度
if (comparison == 0) {
if (aLen < bLen) {
comparison = -1;
} else if (aLen > bLen) {
comparison = 1;
}
}
}
if (comparison != 0) {
return sortOption.order == "asc" ? comparison : -comparison;
}
}
return 0;
});
}
// 应用 skip
if (options != null && options.skip != null) {
const skipValue = options.skip;
if (skipValue > 0) {
results = results.slice(skipValue);
}
}
// 应用 limit
if (options != null && options.limit != null) {
const limitValue = options.limit;
if (limitValue > 0) {
results = results.slice(0, limitValue);
}
}
return results;
}
/**
* 查找单条记录
*/
findOne(id: string | number): RecordWithId<T> | null {
return this.get(id);
}
/**
* 查找第一条匹配的记录
*/
findFirst(where?: QueryCondition<T>): RecordWithId<T> | null {
const results = this.find({ where, limit: 1 });
return results.length > 0 ? results[0] : null;
}
/**
* 统计记录数量
*/
count(where?: QueryCondition<T>): number {
if (where == null) {
return this.getIds().length;
}
return this.find({ where }).length;
}
/**
* 批量插入
* 内部自动分批处理,避免一次性操作过多导致性能问题
* @param items 要插入的数据数组
* @param batchSize 每批处理的条数,默认100条
* 合并默认值
*/
// UTS 不支持 Partial<T>,使用 any 类型
insertMany(items: any[], batchSize: number = 100): (string | number)[] {
const ids: (string | number)[] = [];
const total = items.length;
// 如果数据量小于批次大小,直接处理
if (total <= batchSize) {
for (let i = 0; i < items.length; i++) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(items[i], null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败:`, error);
}
}
return ids;
}
// 大数据量时,分批处理
const batchCount = Math.ceil(total / batchSize);
for (let batch = 0; batch < batchCount; batch++) {
const start = batch * batchSize;
const end = Math.min(start + batchSize, total);
// 处理当前批次
for (let i = start; i < end; i++) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(items[i], null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败 [${i + 1}/${total}]:`, error);
}
}
}
return ids;
}
/**
* 批量更新
*/
updateMany(where: QueryCondition<T>, updates: UpdateData<T>): number {
const records = this.find({ where });
let count = 0;
for (let i = 0; i < records.length; i++) {
const recordAny = records[i] as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as string | number | null;
if (!isNull(idValue) && this.update(idValue as string | number, updates)) {
count++;
}
}
return count;
}
/**
* 批量删除
*/
deleteMany(where: QueryCondition<T>): number {
const records = this.find({ where });
if (records.length == 0) {
return 0;
}
let count = 0;
for (let i = 0; i < records.length; i++) {
const record = records[i];
const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as string | number | null;
if (record != null && !isNull(idValue) && this.delete(idValue as string | number)) {
count++;
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
// UTS 对象属性访问需要使用 UTSJSONObject 方式
private mergeDefaults(data: any): T {
const result = this.deepClone(this.defaults) as T;
const dataKeys = keys(data);
for (const key of dataKeys) {
if (has(this.defaults, key)) {
// UTS 对象属性访问需要使用 get 和 set 函数
const value = get(data, key);
set(result, key, value);
}
}
return count;
return result;
}
/**
* 清空所有记录
* 从列表中移除 ID
*/
clear(): void {
private removeId(id: number | string): void {
const ids = this.getIds();
for (let i = 0; i < ids.length; i++) {
const key = this.getRecordKey(ids[i]);
uni.removeStorageSync(key);
}
this.saveIds([]);
}
/**
* 获取所有记录
*/
findAll(): RecordWithId<T>[] {
// UTS 要求显式传入参数,这里传入空配置对象
const emptyOptions: any = {};
return this.find(emptyOptions as FindOptions<T>);
}
/**
* 创建索引(用于快速查找)
* @param field 要建立索引的字段名
*/
// UTS 不支持 keyof T,使用 string 类型
createIndex(field: string): void {
// 获取所有记录
const records = this.findAll();
// 清空该字段的旧索引
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
// 建立新索引:字段值 -> ID 列表
// UTS 不支持 Record 类型,使用 any 类型
const index: any = {};
for (let i = 0; i < records.length; i++) {
const record = records[i];
// UTS 对象属性访问需要使用 get 函数
const value = get(record, field);
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value == "string" ? value : value.toString()) : "__null__";
// 使用 set 和 get 维护索引,避免直接使用下标访问
// 显式指定空数组类型为 any[]
const emptyArray: any[] = [];
if (!has(index, valueKey)) {
set(index, valueKey, emptyArray);
}
let idList = get(index, valueKey) as any[] | null;
// 确保 idList 不为 null,强制断言为非空数组
if (isNull(idList) || !isArray(idList)) {
idList = [];
}
// 使用非空断言,确保 idList 是数组类型
const idListArray = idList as any[];
const recordAny = record as any;
const idValue = get(recordAny, "id");
// idValue 可能为 null,需要检查后使用类型断言
if (!isNull(idValue)) {
// idListArray 是非空数组,idValue 也不为 null
idListArray.push(idValue as any);
}
set(index, valueKey, idListArray);
}
// 保存索引
uni.setStorageSync(indexKey, index);
}
/**
* 根据索引查找记录
* @param field 索引字段
* @param value 字段值
*/
// UTS 不支持 keyof T,使用 string 类型
findByIndex(field: string, value: any): RecordWithId<T>[] {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
// UTS 不支持 Record 类型,使用 any 类型
const index = uni.getStorageSync(indexKey) as any | null;
if (isNull(index)) {
// 索引不存在,使用普通查询
// UTS 不支持计算属性名 [field],需要先创建对象
const whereCondition: any = {};
set(whereCondition, field, value);
return this.find({ where: whereCondition as QueryCondition<T> });
}
// index 已经检查过不为 null,使用类型断言
// UTS 不支持 Record 类型,使用 any 类型
const indexObj = index as any;
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value == "string" ? value : value.toString()) : "__null__";
// 使用 get 获取 ids,避免下标访问
const idsAny = get(indexObj, valueKey);
if (isNull(idsAny) || !isArray(idsAny)) {
return [];
}
// 确保 ids 是数组类型
const ids = idsAny as any[];
const results: RecordWithId<T>[] = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const record = this.get(id);
if (record != null) {
results.push(record);
}
const index = ids.indexOf(id);
if (index != -1) {
ids.splice(index, 1);
this.saveIds(ids);
}
return results;
}
/**
* 删除索引
*/
// UTS 不支持 keyof T,使用 string 类型
dropIndex(field: string): void {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
}
/**
* 重建所有索引(在数据迁移后使用)
* 保存 ID 列表
*/
// UTS 不支持 keyof T,使用 string[] 类型
rebuildIndexes(fields: string[]): void {
for (let i = 0; i < fields.length; i++) {
this.createIndex(fields[i]);
}
private saveIds(ids: (number | string)[]): void {
uni.setStorageSync(this.idsKey, ids);
}
/**
* 获取存储统计信息
* 验证数据是否符合 schema
*/
getStats(): Stats {
const ids = this.getIds();
let totalSize = 0;
// 估算存储大小(简单实现)
for (let i = 0; i < ids.length; i++) {
const record = this.get(ids[i]);
if (record != null) {
const recordStr = JSON.stringify(record);
totalSize += recordStr.length;
// UTS 不支持 Partial<T>,使用 any 类型
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
private validateData(data: any): boolean {
const dataKeys = keys(data);
for (const key of dataKeys) {
if (!has(this.defaults, key)) {
console.warn(`[LocalStore] 未知字段 "${key}" 在 store "${this.prefix}" 中`);
return false;
}
}
return {
total: ids.length,
size: totalSize
};
return true;
}
}
export default LocalStore;
export type { QueryCondition, FindOptions, SortOption, RecordWithId, UpdateData, Stats };
export type { FindOptions, QueryCondition, RecordWithId, SortOption, Stats, UpdateData };
......@@ -4,7 +4,7 @@ import { forEach, forInObject, isArray, isObject, isString } from "./common";
* 解析数据
* @example parse<Response>(res.data)
*/
export function parse<T>(data: any): T | null {
export function parse<T>(data: any): null | T {
// #ifdef APP-ANDROID
// @ts-ignore
return (data as UTSJSONObject).parse<T>();
......@@ -20,7 +20,7 @@ export function parse<T>(data: any): T | null {
* @param data 要解析的数据
* @returns 解析后的JSON对象
*/
export function parseObject<T>(data: string): T | null {
export function parseObject<T>(data: string): null | T {
// #ifdef APP-ANDROID
return JSON.parseObject<T>(data);
// #endif
......@@ -159,8 +159,8 @@ export const px2rpx = (px: number): number => {
* parseRpx('10px') // 返回 '10px'
*/
export const parseRpx = (val: number | string): string => {
if (typeof val == "number") {
return val + "rpx";
if (typeof val === "number") {
return `${val }rpx`;
}
return val;
......@@ -179,7 +179,7 @@ export const parseRpx = (val: number | string): string => {
export const getNum = (val: string): number => {
// 使用正则提取数字部分,支持小数和负数
const match = val.match(/-?\d+(\.\d+)?/);
return match != null ? parseFloat(match[0] ?? "0") : 0;
return match != null ? Number.parseFloat(match[0] ?? "0") : 0;
};
/**
......@@ -205,7 +205,7 @@ export const getUnit = (val: string): string => {
* @returns number - 返回对应的 rpx 数值
*/
export const getRpx = (val: number | string): number => {
if (typeof val == "number") {
if (typeof val === "number") {
return val;
}
......@@ -228,8 +228,8 @@ export const getRpx = (val: number | string): number => {
* @param val - 输入值,可以是 "10rpx"、"10px" 或数字 10
* @returns number - 返回对应的 px 数值
*/
export const getPx = (val: string | number) => {
if (typeof val == "number") {
export const getPx = (val: number | string) => {
if (typeof val === "number") {
return rpx2px(val);
}
......
......@@ -59,12 +59,12 @@ export function openAppSettings(): void {
*/
export function getInstalledPackages(): Promise<
Array<{
appName: string;
packName: string;
versionName: string;
versionCode: number;
appName: string;
versionName: string;
}>
> {
> {
// #ifdef APP-ANDROID
const packages = androidImpl.getInstalledPackages();
return Promise.resolve(packages);
......
......@@ -60,8 +60,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.readFile({
filePath: filePath,
encoding: encoding,
filePath,
encoding,
success: (res: any) => {
// ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer
// 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理
......@@ -77,10 +77,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
if (parsed != null) {
const temp = parsed.getAny("data");
console.error("readFile getAny('data'): ", temp);
console.error("readFile getAny('data'):", temp);
raw = temp != null ? temp as any : null;
}
} catch (e: any) {
} catch {
// 方法2:如果 parseObject 失败,尝试用普通 parse
try {
......@@ -90,16 +90,16 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// 尝试从解析后的对象中获取 data
if (parsed != null) {
const temp = get(parsed as UTSJSONObject, "data");
console.error("readFile get('data'): ", temp);
console.error("readFile get('data'):", temp);
raw = temp != null ? temp as any : null;
}
} catch (e2: any) {
console.error("readFile method2 failed: ", e2);
} catch (error: any) {
console.error("readFile method2 failed:", error);
}
}
if (raw != null) {
if (typeof raw == "string") {
if (typeof raw === "string") {
text = raw as string;
} else {
// ArrayBuffer 类型,需要转换为字符串
......@@ -110,8 +110,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// @ts-ignore
const decoder = new TextDecoder("utf-8");
text = decoder.decode(raw as ArrayBuffer);
} catch (e: any) {
console.error("ArrayBuffer decode error: ", e);
} catch (error: any) {
console.error("ArrayBuffer decode error:", error);
text = "";
}
// #endif
......@@ -121,11 +121,11 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// #endif
}
}
console.error("readFile text final: ", text);
console.error("readFile text final:", text);
resolve(text);
},
fail: (err: any) => {
console.error("readFile fail: ", err);
console.error("readFile fail:", err);
reject(err);
}
});
......@@ -141,8 +141,8 @@ export function writeFile(filePath: string, data: string): Promise<void> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.writeFile({
filePath: filePath,
data: data,
filePath,
data,
encoding: "utf-8",
success: () => {
resolve();
......@@ -162,7 +162,7 @@ export function deleteFile(filePath: string): Promise<void> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.unlink({
filePath: filePath,
filePath,
success: () => {
resolve();
},
......@@ -181,10 +181,10 @@ export function readDirectory(dirPath: string): Promise<string[]> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.readdir({
dirPath: dirPath,
dirPath,
success: (res: any) => {
const files = res.files;
if (files instanceof Array) {
if (Array.isArray(files)) {
resolve(files as string[]);
} else {
resolve([]);
......@@ -206,8 +206,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.mkdir({
dirPath: dirPath,
recursive: recursive,
dirPath,
recursive,
success: () => {
resolve();
},
......@@ -227,8 +227,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.rmdir({
dirPath: dirPath,
recursive: recursive,
dirPath,
recursive,
success: () => {
resolve();
},
......
......@@ -35,7 +35,7 @@ export function setUserAgent(userAgent: string): void {
// #ifndef APP
// H5 可以设置 navigator.userAgent
if (typeof navigator != "undefined") {
if (typeof navigator !== "undefined") {
Object.defineProperty(navigator, "userAgent", {
get: () => userAgent,
configurable: true
......
......@@ -11,8 +11,8 @@ import { openSchema } from "@/uni_modules/uts-openSchema";
// 应用信息类型
type AppInfo = {
version: string;
appid: string;
version: string;
};
/**
......@@ -32,8 +32,8 @@ export function getAppVersion(): string {
}
}
// #endif
} catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败: ", e);
} catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败:", error);
}
// 其它平台或获取失败时返回空字符串,由上层决定是否展示
......@@ -55,8 +55,8 @@ export function getAppId(): string {
}
}
// #endif
} catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败: ", e);
} catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败:", error);
}
return "";
......@@ -67,7 +67,7 @@ export function getAppId(): string {
* @param url 要打开的URL
*/
export function openURL(url: string): void {
if (url == null || url.length == 0) {
if (url == null || url.length === 0) {
console.error("[plus-runtime] URL不能为空");
return;
}
......@@ -78,14 +78,14 @@ export function openURL(url: string): void {
try {
openSchema(url);
return;
} catch (e: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败: ", e, " url=", url);
} catch (error: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败:", error, "url=", url);
}
// #endif
// 其它平台或兜底逻辑:H5 使用 window.open
// #ifndef APP
if (typeof window != "undefined") {
if (typeof window !== "undefined") {
window.open(url, "_blank");
}
// #endif
......
import { PAGES, TABS } from "./ctx";
import type { BackOptions, PageInstance, PushOptions } from "../types/router";
import {
storage,
last,
isNull,
isEmpty,
debounce,
get,
isEmpty,
isFunction,
toArray,
isNull,
last,
map,
debounce,
nth,
assign,
parse
storage,
toArray
} from "../utils";
import { PAGES, TABS } from "./ctx";
// 路由信息类型
type RouteInfo = {
isAuth?: boolean;
meta: UTSJSONObject;
path: string;
query: UTSJSONObject;
meta: UTSJSONObject;
isAuth?: boolean;
};
// 跳转前钩子类型
......@@ -30,22 +29,81 @@ type AfterLogin = () => void;
// 路由事件集合
type Events = {
beforeEach?: BeforeEach;
afterLogin?: AfterLogin;
beforeEach?: BeforeEach;
};
// 路由核心类
export class Router {
// 跳转到登录页(防抖处理)
login = debounce(() => {
if (!this.isLoginPage(this.path())) {
this.push({
path: "/pages/user/login",
mode: "reLaunch"
});
}
}, 300);
private eventsMap = {} as Events; // 事件存储
// 获取传递的 params 参数
params() {
return (storage.get("router-params") ?? {}) as UTSJSONObject;
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
}
// 获取传递的 query 参数
query() {
return this.route()?.query ?? {};
// 返回上一页
back(options: BackOptions | null = null) {
if (this.isFirstPage()) {
this.home();
} else {
const delta = options?.delta ?? 1;
// 执行跳转函数
const next = () => {
uni.navigateBack({ ...options });
};
// 跳转前钩子处理
if (this.eventsMap.beforeEach != null) {
// 当前页
const from = last(this.getPages());
// 上一页
const to = nth(this.getPages(), -delta - 1);
if (to != null) {
// 调用跳转前钩子
this.eventsMap.beforeEach(
{
path: to.path,
query: to.query,
meta: to.meta ?? ({} as UTSJSONObject)
},
from!,
next
);
} else {
console.error("[router] found to page is null");
}
} else {
next();
}
}
}
// 注册跳转前钩子
beforeEach(cb: BeforeEach) {
this.eventsMap.beforeEach = cb;
}
// 执行当前页面暴露的方法
callMethod(name: string, data?: any): any | null {
const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null;
if (isFunction(fn)) {
return fn(data);
}
return null;
}
// 获取默认路径,支持 home 和 login
......@@ -58,6 +116,16 @@ export class Router {
return get(paths, name) as string;
}
// 获取页面元数据
getMeta(path: string) {
return PAGES.find((e) => path.includes(e.path))?.meta ?? ({} as UTSJSONObject);
}
// 获取指定路径的页面实例
getPage(path: string) {
return this.getPages().find((e) => e.path == path);
}
// 获取当前页面栈的所有页面实例
getPages(): PageInstance[] {
return map(getCurrentPages(), (e) => {
......@@ -70,7 +138,7 @@ export class Router {
// 补全路径前缀
if (!path.startsWith("/")) {
path = "/" + path;
path = `/${ path}`;
}
// 获取页面样式
......@@ -104,14 +172,76 @@ export class Router {
});
}
// 获取指定路径的页面实例
getPage(path: string) {
return this.getPages().find((e) => e.path == path);
// 回到首页
home() {
this.push({
path: this.defaultPath("home")
});
}
// 获取当前路由页面实例
route() {
return last(this.getPages());
// 判断是否为当前页面
isCurrentPage(path: string) {
return this.path() == path;
}
// 判断是否为自定义导航栏页面
isCustomNavbarPage() {
return this.route()?.isCustomNavbar ?? false;
}
// 判断页面栈是否只有一个页面
isFirstPage() {
return getCurrentPages().length == 1;
}
// 判断是否为首页
isHomePage() {
return this.path() == this.defaultPath("home");
}
// 判断是否为登录页
isLoginPage(path: string) {
return path == this.defaultPath("login");
}
// 判断是否为 tab 页面
isTabPage(path: null | string = null) {
if (path == null) {
path = this.path();
}
if (path == "/") {
path = this.defaultPath("home");
}
return !isNull(TABS.find((e) => path == e.pagePath));
}
// 登录成功后跳转逻辑
nextLogin() {
const pages = this.getPages();
// 找到登录页的索引
const index = pages.findIndex((e) => this.defaultPath("login").includes(e.path));
// 未找到,则跳回首页
if (index === -1) {
this.home();
} else {
this.back({
delta: pages.length - index
});
}
// 登录后回调
if (this.eventsMap.afterLogin != null) {
this.eventsMap.afterLogin!();
}
// 触发全局 afterLogin 事件
uni.$emit("afterLogin");
}
// 获取传递的 params 参数
params() {
return (storage.get("router-params") ?? {}) as UTSJSONObject;
}
// 获取当前页面路径
......@@ -119,13 +249,6 @@ export class Router {
return this.route()?.path ?? "";
}
// 简单跳转页面(默认 navigateTo)
to(path: string) {
this.push({
path
});
}
// 路由跳转,支持多种模式和参数
push(options: PushOptions) {
let {
......@@ -147,7 +270,7 @@ export class Router {
const arr = toArray(query, (v, k) => {
return `${k}=${v}`;
});
path += "?" + arr.join("&");
path += `?${ arr.join("&")}`;
}
// params 通过 storage 临时存储
......@@ -163,7 +286,7 @@ export class Router {
// 跳转执行函数
const next = () => {
switch (mode) {
case "navigateTo":
case "navigateTo": {
uni.navigateTo({
url: path,
success,
......@@ -174,7 +297,8 @@ export class Router {
animationDuration
});
break;
case "redirectTo":
}
case "redirectTo": {
uni.redirectTo({
url: path,
success,
......@@ -182,7 +306,8 @@ export class Router {
complete
});
break;
case "reLaunch":
}
case "reLaunch": {
uni.reLaunch({
url: path,
success,
......@@ -190,7 +315,8 @@ export class Router {
complete
});
break;
case "switchTab":
}
case "switchTab": {
uni.switchTab({
url: path,
success,
......@@ -198,6 +324,7 @@ export class Router {
complete
});
break;
}
}
};
......@@ -216,145 +343,21 @@ export class Router {
}
}
// 回到首页
home() {
this.push({
path: this.defaultPath("home")
});
}
// 返回上一页
back(options: BackOptions | null = null) {
if (this.isFirstPage()) {
this.home();
} else {
const delta = options?.delta ?? 1;
// 执行跳转函数
const next = () => {
uni.navigateBack({ ...(options ?? {}) });
};
// 跳转前钩子处理
if (this.eventsMap.beforeEach != null) {
// 当前页
const from = last(this.getPages());
// 上一页
const to = nth(this.getPages(), -delta - 1);
if (to != null) {
// 调用跳转前钩子
this.eventsMap.beforeEach(
{
path: to.path,
query: to.query,
meta: to.meta ?? ({} as UTSJSONObject)
},
from!,
next
);
} else {
console.error("[router] found to page is null");
}
} else {
next();
}
}
}
// 获取页面元数据
getMeta(path: string) {
return PAGES.find((e) => path.includes(e.path))?.meta ?? ({} as UTSJSONObject);
}
// 执行当前页面暴露的方法
callMethod(name: string, data?: any): any | null {
const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null;
if (isFunction(fn)) {
return fn(data);
}
return null;
}
// 判断页面栈是否只有一个页面
isFirstPage() {
return getCurrentPages().length == 1;
}
// 判断是否为首页
isHomePage() {
return this.path() == this.defaultPath("home");
}
// 判断是否为自定义导航栏页面
isCustomNavbarPage() {
return this.route()?.isCustomNavbar ?? false;
}
// 判断是否为当前页面
isCurrentPage(path: string) {
return this.path() == path;
}
// 判断是否为 tab 页面
isTabPage(path: string | null = null) {
if (path == null) {
path = this.path();
}
if (path == "/") {
path = this.defaultPath("home");
}
return !isNull(TABS.find((e) => path == e.pagePath));
}
// 判断是否为登录页
isLoginPage(path: string) {
return path == this.defaultPath("login");
}
// 跳转到登录页(防抖处理)
login = debounce(() => {
if (!this.isLoginPage(this.path())) {
this.push({
path: "/pages/user/login",
mode: "reLaunch"
});
}
}, 300);
// 登录成功后跳转逻辑
nextLogin() {
const pages = this.getPages();
// 找到登录页的索引
const index = pages.findIndex((e) => this.defaultPath("login").includes(e.path));
// 未找到,则跳回首页
if (index < 0) {
this.home();
} else {
this.back({
delta: pages.length - index
});
}
// 登录后回调
if (this.eventsMap.afterLogin != null) {
this.eventsMap.afterLogin!();
}
// 触发全局 afterLogin 事件
uni.$emit("afterLogin");
// 获取传递的 query 参数
query() {
return this.route()?.query ?? {};
}
// 注册跳转前钩子
beforeEach(cb: BeforeEach) {
this.eventsMap.beforeEach = cb;
// 获取当前路由页面实例
route() {
return last(this.getPages());
}
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
// 简单跳转页面(默认 navigateTo)
to(path: string) {
this.push({
path
});
}
}
......
......@@ -17,20 +17,20 @@ export interface ScreenInfo {
* 获取屏幕信息
*/
export function getScreenInfo(): ScreenInfo {
const windowInfo = uni.getWindowInfo()
const windowInfo = uni.getWindowInfo();
return {
width: windowInfo.windowWidth,
height: windowInfo.windowHeight,
pixelRatio: windowInfo.pixelRatio,
screenWidth: windowInfo.screenWidth,
screenHeight: windowInfo.screenHeight
}
};
}
/**
* 屏幕尺寸分类
*/
export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge'
export type ScreenSize = "large" | "medium" | "small" | "xlarge"
/**
* 获取屏幕尺寸分类
......@@ -40,15 +40,15 @@ export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge'
* - xlarge: >= 1024px(平板、大屏设备)
*/
export function getScreenSize(): ScreenSize {
const width = getScreenInfo().width
const width = getScreenInfo().width;
if (width < 480) {
return 'small'
return "small";
} else if (width < 768) {
return 'medium'
return "medium";
} else if (width < 1024) {
return 'large'
return "large";
} else {
return 'xlarge'
return "xlarge";
}
}
......@@ -68,25 +68,25 @@ export function getScreenSize(): ScreenSize {
* const fontSize = responsiveFontSize(14, 12, 20)
*/
export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSize: number = 48): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
// 设计稿基准宽度(通常为 375px 或 750px)
// 如果设计稿是 750px,这里改为 750,baseSize 也需要相应调整
const designWidth = 375
const designWidth = 375;
// 计算缩放比例(限制在合理范围内)
const scale = screenWidth / designWidth
const scaledSize = baseSize * scale
const scale = screenWidth / designWidth;
const scaledSize = baseSize * scale;
// 限制在最小值和最大值之间
if (scaledSize < minSize) {
return minSize
return minSize;
} else if (scaledSize > maxSize) {
return maxSize
return maxSize;
}
return Math.round(scaledSize)
return Math.round(scaledSize);
}
/**
......@@ -104,20 +104,20 @@ export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSi
* const padding = responsiveSpacing(16, 12, 24)
*/
export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
const designWidth = 375;
const scale = screenWidth / designWidth
const scaledSpacing = baseSpacing * scale
const scale = screenWidth / designWidth;
const scaledSpacing = baseSpacing * scale;
if (scaledSpacing < minSpacing) {
return minSpacing
return minSpacing;
} else if (scaledSpacing > maxSpacing) {
return maxSpacing
return maxSpacing;
}
return Math.round(scaledSpacing)
return Math.round(scaledSpacing);
}
/**
......@@ -133,35 +133,35 @@ export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, m
* const buttonWidth = responsiveWidth(200)
*/
export function responsiveWidth(baseWidth: number): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
const designWidth = 375;
return Math.round(baseWidth * (screenWidth / designWidth))
return Math.round(baseWidth * (screenWidth / designWidth));
}
/**
* 判断是否为横屏
*/
export function isLandscape(): boolean {
const screenInfo = getScreenInfo()
return screenInfo.width > screenInfo.height
const screenInfo = getScreenInfo();
return screenInfo.width > screenInfo.height;
}
/**
* 判断是否为平板尺寸
*/
export function isTablet(): boolean {
const screenSize = getScreenSize()
return screenSize === 'large' || screenSize === 'xlarge'
const screenSize = getScreenSize();
return screenSize === "large" || screenSize === "xlarge";
}
/**
* 判断是否为手机尺寸
*/
export function isMobile(): boolean {
const screenSize = getScreenSize()
return screenSize === 'small' || screenSize === 'medium'
const screenSize = getScreenSize();
return screenSize === "small" || screenSize === "medium";
}
/**
......@@ -175,5 +175,5 @@ export function isMobile(): boolean {
* const columns = getColumns(1, 2)
*/
export function getColumns(mobileColumns: number = 1, tabletColumns: number = 2): number {
return isTablet() ? tabletColumns : mobileColumns
return isTablet() ? tabletColumns : mobileColumns;
}
......@@ -8,14 +8,16 @@
* 2. iOS平台需要自定义基座
*/
import type { DatabaseOptions, SqlOperationOptions } from "@/uni_modules/lime-sqlite";
import {
openDatabase,
closeDatabase,
executeSql,
selectSql,
isOpenDatabase,
type DatabaseOptions,
type SqlOperationOptions
openDatabase,
selectSql
} from "@/uni_modules/lime-sqlite";
// 说明:
......@@ -24,8 +26,8 @@ import {
// - 这里在业务侧声明一个结构兼容的类型,避免跨端编译/运行时报错
type SQLiteSuccess = {
data: any[];
result: UTSJSONObject[];
errMsg: string;
result: UTSJSONObject[];
};
// 定义回调函数类型
......@@ -45,12 +47,12 @@ class SqliteStore {
// 数据库名称
private dbName: string;
// 表名
private tableName: string;
// 数据库是否已初始化
private initialized: boolean = false;
// 表名
private tableName: string;
/**
* 构造函数
* @param name 表名
......@@ -62,10 +64,166 @@ class SqliteStore {
}
/**
* 清空表
* @param success 成功回调
* @param fail 失败回调
*/
clear(success: SuccessCallback, fail: FailCallback): void {
const sql = `DELETE FROM ${this.tableName}`;
const clearOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 清空表成功: ${this.tableName}`);
success(res);
},
fail
} as SqlOperationOptions;
executeSql(clearOptions);
}
/**
* 关闭数据库连接
*/
close(): void {
const closeOptions = {
name: this.dbName,
success: (res: any) => {
console.log(`[SqliteStore] 数据库 ${this.dbName} 关闭成功`);
},
fail: (err: any) => {
console.error(`[SqliteStore] 数据库 ${this.dbName} 关闭失败:`, err);
}
} as DatabaseOptions;
closeDatabase(closeOptions);
}
/**
* 统计记录数
* @param success 成功回调
* @param fail 失败回调
*/
count(
success: CountSuccessCallback,
fail: FailCallback
): void {
const sql = `SELECT COUNT(*) as total FROM ${this.tableName}`;
const countOptions = {
name: this.dbName,
sql: [sql],
// 同样使用 any 作为参数类型,保持与插件类型解耦
success: (res: any) => {
// 统计查询同样返回 SQLiteSuccess,对 data/result 统一处理
console.log(`[SqliteStore] count res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 同样优先使用 result(对象数组,包含 total 字段)
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length > 0) {
const row = rows[0] as UTSJSONObject;
const total = row.get("total") as number;
success(total);
} else {
success(0);
}
},
fail
} as SqlOperationOptions;
selectSql(countOptions);
}
/**
* 删除记录
* @param id 记录 ID
* @param success 成功回调
* @param fail 失败回调
*/
deleteById(
id: string,
success: null | SuccessCallback,
fail: FailCallback | null
): void {
const sql = `DELETE FROM ${this.tableName} WHERE id = '${id}'`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 删除成功: ${id}`);
if (success != null) {
success(res);
}
},
fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 批量删除
* @param ids ID 数组
* @param success 成功回调
* @param fail 失败回调
*/
deleteMany(
ids: any,
success: SuccessCallback,
fail: FailCallback
): void {
const idList = ids as string[];
const sql = `DELETE FROM ${this.tableName} WHERE id IN ('${idList.join("','")}')`;
const deleteManyOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 批量删除成功: ${idList.length} 条`);
success(res);
},
fail
} as SqlOperationOptions;
executeSql(deleteManyOptions);
}
/**
* 执行 SQL 语句(增删改)
* @param sqls SQL 语句数组
* @param success 成功回调
* @param fail 失败回调
*/
executeSql(
sqls: string[],
success: null | SuccessCallback,
fail: FailCallback | null
): void {
executeSql({
name: this.dbName,
sql: sqls,
success: (res) => {
if (success != null) {
success(res);
}
},
fail: (err) => {
console.error(`[SqliteStore] SQL 执行失败:`, err);
if (fail != null) {
fail(err);
}
}
} as SqlOperationOptions);
}
/**
* 初始化数据库和表结构
* @param callback 初始化完成后的回调函数
*/
init(callback: SuccessCallback | null): void {
init(callback: null | SuccessCallback): void {
// 打开数据库
openDatabase({
name: this.dbName,
......@@ -80,40 +238,59 @@ class SqliteStore {
}
/**
* 创建表结构
* 表结构:id (主键), name, age, email, status, created_at, updated_at
* 插入记录
* @param data 记录数据
* @param success 成功回调
* @param fail 失败回调
*/
private createTable(callback: SuccessCallback | null): void {
insert(
data: any,
success: InsertSuccessCallback,
fail: FailCallback
): void {
const id = `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
const now = Date.now();
// 将 data 转换为 UTSJSONObject 以访问属性
const dataObj = data as UTSJSONObject;
const name = dataObj.get("name") as string;
const age = dataObj.get("age") as number;
const email = dataObj.get("email") as string;
const status = dataObj.get("status") as string;
const escapedName = name == null ? "" : name.replaceAll("'", "''");
const escapedEmail = email == null ? "" : email.replaceAll("'", "''");
const escapedStatus = status == null ? "" : status.replaceAll("'", "''");
const sql = `
CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT,
age INTEGER,
email TEXT,
status TEXT,
created_at INTEGER,
updated_at INTEGER
)
INSERT INTO ${this.tableName} (id, name, age, email, status, created_at, updated_at)
VALUES ('${id}', '${escapedName}', ${age}, '${escapedEmail}', '${escapedStatus}', ${now}, ${now})
`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 表 ${this.tableName} 创建成功`);
this.initialized = true;
if (callback != null) {
callback(res);
}
console.log(`[SqliteStore] 插入成功: ${id}`);
success(id);
},
fail: (err: any) => {
console.error(`[SqliteStore] 表 ${this.tableName} 创建失败:`, err);
}
fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 批量插入
* @param dataList 数据数组
* @param success 成功回调
* @param fail 失败回调
*/
insertMany(
dataList: any,
success: InsertManySuccessCallback,
fail: FailCallback
): void {}
/**
* 检查数据库是否打开
* @returns 是否打开
*/
......@@ -129,31 +306,44 @@ class SqliteStore {
}
/**
* 执行 SQL 语句(增删改)
* @param sqls SQL 语句数组
* 查询所有记录
* @param success 成功回调
* @param fail 失败回调
*/
executeSql(
sqls: string[],
success: SuccessCallback | null,
fail: FailCallback | null
select(
success: SelectSuccessCallback,
fail?: FailCallback | null
): void {
executeSql({
const sql = `SELECT * FROM ${this.tableName} ORDER BY created_at DESC`;
const options = {
name: this.dbName,
sql: sqls,
success: (res) => {
if (success != null) {
success(res);
sql: [sql],
// 注意:这里使用 any 作为参数类型,避免与 lime-sqlite 内部的 SQLiteSuccess 名称冲突
// 然后在函数体内按我们约定的结构进行访问
success: (res: any) => {
// lime-sqlite 返回 SQLiteSuccess 对象,data 为原始数组,result 为对象数组
console.log(`[SqliteStore] 原始 res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 页面代码普遍按 UTSJSONObject 来读取字段(row.get("xxx")),
// 因此优先使用 result(对象数组),只有在没有 result 时才退回 data。
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
},
fail: (err) => {
console.error(`[SqliteStore] SQL 执行失败:`, err);
if (fail != null) {
fail(err);
if (rows.length === 0) {
console.log(`[SqliteStore] 没有找到数据,返回空数组`);
}
}
} as SqlOperationOptions);
success(rows);
},
fail
} as SqlOperationOptions;
selectSql(options);
}
/**
......@@ -164,7 +354,7 @@ class SqliteStore {
*/
selectSql(
sqls: string[],
success: SelectSuccessCallback | null,
success: null | SelectSuccessCallback,
fail: FailCallback | null
): void {
const selectOptions = {
......@@ -191,9 +381,9 @@ class SqliteStore {
resultData = parsed as any[];
} else {
// 是对象,使用方括号语法访问属性
const data = parsed['data'];
const rows = parsed['rows'];
const result = parsed['result'];
const data = parsed.data;
const rows = parsed.rows;
const result = parsed.result;
console.log(`[SqliteStore] data:`, data);
console.log(`[SqliteStore] rows:`, rows);
......@@ -230,47 +420,6 @@ class SqliteStore {
}
/**
* 插入记录
* @param data 记录数据
* @param success 成功回调
* @param fail 失败回调
*/
insert(
data: any,
success: InsertSuccessCallback,
fail: FailCallback
): void {
const id = `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
const now = Date.now();
// 将 data 转换为 UTSJSONObject 以访问属性
const dataObj = data as UTSJSONObject;
const name = dataObj.get("name") as string;
const age = dataObj.get("age") as number;
const email = dataObj.get("email") as string;
const status = dataObj.get("status") as string;
const escapedName = name == null ? "" : name.replace(/'/g, "''");
const escapedEmail = email == null ? "" : email.replace(/'/g, "''");
const escapedStatus = status == null ? "" : status.replace(/'/g, "''");
const sql = `
INSERT INTO ${this.tableName} (id, name, age, email, status, created_at, updated_at)
VALUES ('${id}', '${escapedName}', ${age}, '${escapedEmail}', '${escapedStatus}', ${now}, ${now})
`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 插入成功: ${id}`);
success(id);
},
fail: fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 更新记录
* @param id 记录 ID
* @param data 更新数据
......@@ -280,7 +429,7 @@ class SqliteStore {
update(
id: string,
data: any,
success: SuccessCallback | null,
success: null | SuccessCallback,
fail: FailCallback | null
): void {
const now = Date.now();
......@@ -291,7 +440,7 @@ class SqliteStore {
const name = dataObj.get("name");
if (name != null) {
const escapedName = (name as string).replace(/'/g, "''");
const escapedName = (name as string).replaceAll("'", "''");
updates.push(`name = '${escapedName}'`);
}
......@@ -302,13 +451,13 @@ class SqliteStore {
const email = dataObj.get("email");
if (email != null) {
const escapedEmail = (email as string).replace(/'/g, "''");
const escapedEmail = (email as string).replaceAll("'", "''");
updates.push(`email = '${escapedEmail}'`);
}
const status = dataObj.get("status");
if (status != null) {
const escapedStatus = (status as string).replace(/'/g, "''");
const escapedStatus = (status as string).replaceAll("'", "''");
updates.push(`status = '${escapedStatus}'`);
}
......@@ -329,193 +478,44 @@ class SqliteStore {
success(res);
}
},
fail: fail
fail
} as SqlOperationOptions;
executeSql(updateOptions);
}
/**
* 删除记录
* @param id 记录 ID
* @param success 成功回调
* @param fail 失败回调
*/
deleteById(
id: string,
success: SuccessCallback | null,
fail: FailCallback | null
): void {
const sql = `DELETE FROM ${this.tableName} WHERE id = '${id}'`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 删除成功: ${id}`);
if (success != null) {
success(res);
}
},
fail: fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 查询所有记录
* @param success 成功回调
* @param fail 失败回调
*/
select(
success: SelectSuccessCallback,
fail?: FailCallback | null
): void {
const sql = `SELECT * FROM ${this.tableName} ORDER BY created_at DESC`;
const options = {
name: this.dbName,
sql: [sql],
// 注意:这里使用 any 作为参数类型,避免与 lime-sqlite 内部的 SQLiteSuccess 名称冲突
// 然后在函数体内按我们约定的结构进行访问
success: (res: any) => {
// lime-sqlite 返回 SQLiteSuccess 对象,data 为原始数组,result 为对象数组
console.log(`[SqliteStore] 原始 res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 页面代码普遍按 UTSJSONObject 来读取字段(row.get("xxx")),
// 因此优先使用 result(对象数组),只有在没有 result 时才退回 data。
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length == 0) {
console.log(`[SqliteStore] 没有找到数据,返回空数组`);
}
success(rows);
},
fail: fail
} as SqlOperationOptions;
selectSql(options);
}
/**
* 批量插入
* @param dataList 数据数组
* @param success 成功回调
* @param fail 失败回调
*/
insertMany(
dataList: any,
success: InsertManySuccessCallback,
fail: FailCallback
): void {
}
/**
* 批量删除
* @param ids ID 数组
* @param success 成功回调
* @param fail 失败回调
* 创建表结构
* 表结构:id (主键), name, age, email, status, created_at, updated_at
*/
deleteMany(
ids: any,
success: SuccessCallback,
fail: FailCallback
): void {
const idList = ids as string[];
const sql = `DELETE FROM ${this.tableName} WHERE id IN ('${idList.join("','")}')`;
const deleteManyOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 批量删除成功: ${idList.length} 条`);
success(res);
},
fail: fail
} as SqlOperationOptions;
executeSql(deleteManyOptions);
}
private createTable(callback: null | SuccessCallback): void {
const sql = `
CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT,
age INTEGER,
email TEXT,
status TEXT,
created_at INTEGER,
updated_at INTEGER
)
`;
/**
* 统计记录数
* @param success 成功回调
* @param fail 失败回调
*/
count(
success: CountSuccessCallback,
fail: FailCallback
): void {
const sql = `SELECT COUNT(*) as total FROM ${this.tableName}`;
const countOptions = {
const options = {
name: this.dbName,
sql: [sql],
// 同样使用 any 作为参数类型,保持与插件类型解耦
success: (res: any) => {
// 统计查询同样返回 SQLiteSuccess,对 data/result 统一处理
console.log(`[SqliteStore] count res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 同样优先使用 result(对象数组,包含 total 字段)
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length > 0) {
const row = rows[0] as UTSJSONObject;
const total = row.get("total") as number;
success(total);
} else {
success(0);
console.log(`[SqliteStore] 表 ${this.tableName} 创建成功`);
this.initialized = true;
if (callback != null) {
callback(res);
}
},
fail: fail
} as SqlOperationOptions;
selectSql(countOptions);
}
/**
* 清空表
* @param success 成功回调
* @param fail 失败回调
*/
clear(success: SuccessCallback, fail: FailCallback): void {
const sql = `DELETE FROM ${this.tableName}`;
const clearOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 清空表成功: ${this.tableName}`);
success(res);
},
fail: fail
} as SqlOperationOptions;
executeSql(clearOptions);
}
/**
* 关闭数据库连接
*/
close(): void {
const closeOptions = {
name: this.dbName,
success: (res: any) => {
console.log(`[SqliteStore] 数据库 ${this.dbName} 关闭成功`);
},
fail: (err: any) => {
console.error(`[SqliteStore] 数据库 ${this.dbName} 关闭失败:`, err);
console.error(`[SqliteStore] 表 ${this.tableName} 创建失败:`, err);
}
} as DatabaseOptions;
closeDatabase(closeOptions);
} as SqlOperationOptions;
executeSql(options);
}
}
......
......@@ -9,6 +9,18 @@ const EXPIRES_SUFFIX = "_deadtime";
*/
class Storage {
/**
* 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取存储数据
*
* @param key 存储键名
......@@ -52,32 +64,6 @@ class Storage {
}
/**
* 设置存储数据
*
* @param key 存储键名
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
*
* @example
* // 存储永久数据
* storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/
set(key: string, value: any, expires: number): void {
// 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = new Date().getTime() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
}
/**
* 检查数据是否已过期
*
* @param key 存储键名
......@@ -90,7 +76,7 @@ class Storage {
*/
isExpired(key: string): boolean {
// 获取过期时间戳
const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as number | null;
const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as null | number;
// 如果没有设置过期时间,视为已过期
if (value == null) {
......@@ -98,7 +84,29 @@ class Storage {
}
// 比较过期时间戳与当前时间,判断是否过期
return value - new Date().getTime() <= 0;
return value - Date.now() <= 0;
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
*
* @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null
*
* @example
* const tempToken = storage.once('temp_token');
* // tempToken 使用后,存储中的 temp_token 已被删除
*/
once(key: string): any | null {
// 先获取数据
const value = this.get(key);
// 立即删除数据
this.remove(key);
// 返回获取到的数据
return value;
}
/**
......@@ -120,37 +128,29 @@ class Storage {
}
/**
* 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
* 设置存储数据
*
* @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
*
* @example
* const tempToken = storage.once('temp_token');
* // tempToken 使用后,存储中的 temp_token 已被删除
* // 存储永久数据
* storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/
once(key: string): any | null {
// 先获取数据
const value = this.get(key);
// 立即删除数据
this.remove(key);
// 返回获取到的数据
return value;
set(key: string, value: any, expires: number): void {
// 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = Date.now() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
}
}
......
// utils/theme-classes.uts
// 主题化类名工具函数 - 让主题系统像 Tailwind 一样使用类名
import { getThemeManager } from './theme-manager.uts'
import { getThemeManager } from "./theme-manager.uts";
/**
* Tailwind 风格类名工具函数
......@@ -15,17 +15,17 @@ import { getThemeManager } from './theme-manager.uts'
* // 返回: 'theme-mobile-medium p-4 rounded-lg'
*/
export function tw(...classes: string[]): string {
const themeManager = getThemeManager()
const themeName = themeManager.getCurrentThemeName()
const themePrefix = `theme-${themeName}`
return [themePrefix, ...classes].join(' ')
const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName();
const themePrefix = `theme-${themeName}`;
return [themePrefix, ...classes].join(" ");
}
/**
* 获取当前主题前缀
*/
export function getThemePrefix(): string {
const themeManager = getThemeManager()
const themeName = themeManager.getCurrentThemeName()
return `theme-${themeName}`
const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName();
return `theme-${themeName}`;
}
// utils/theme-manager.uts
// 主题管理器 - 类似 i18n,管理多套主题的切换和获取
import { getScreenSize } from './screen-adapt.uts'
import { get } from './common.uts'
import { get } from "./common.uts";
import { getScreenSize } from "./screen-adapt.uts";
/**
* 主题名称类型
*/
export type ThemeName = 'mobile-small' | 'mobile-medium' | 'mobile-large' | 'tablet' | 'tablet-large'
export type ThemeName = "mobile-large" | "mobile-medium" | "mobile-small" | "tablet" | "tablet-large"
/**
* 主题变量接口
......@@ -42,42 +42,42 @@ export type ThemeConfig = {
* 实际项目中可以改为从 themes/themes.json 文件读取
*/
const defaultThemeConfig: ThemeConfig = {
'mobile-small': {
spacing: { '0': 0, xs: 4, sm: 6, md: 10, base: 12, lg: 16, xl: 20, '2xl': 24, '3xl': 32, '4xl': 40 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 10, '2xl': 12, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 28, '4xl': 32 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, '2xl': 80, '3xl': 96 },
"mobile-small": {
spacing: { "0": 0, xs: 4, sm: 6, md: 10, base: 12, lg: 16, xl: 20, "2xl": 24, "3xl": 32, "4xl": 40 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 10, "2xl": 12, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, "2xl": 24, "3xl": 28, "4xl": 32 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, "2xl": 80, "3xl": 96 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
},
'mobile-medium': {
spacing: { '0': 0, xs: 4, sm: 8, md: 12, base: 16, lg: 20, xl: 24, '2xl': 32, '3xl': 40, '4xl': 48 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 12, '2xl': 16, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 30, '4xl': 36 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, '2xl': 80, '3xl': 96 },
"mobile-medium": {
spacing: { "0": 0, xs: 4, sm: 8, md: 12, base: 16, lg: 20, xl: 24, "2xl": 32, "3xl": 40, "4xl": 48 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 12, "2xl": 16, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, "2xl": 24, "3xl": 30, "4xl": 36 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, "2xl": 80, "3xl": 96 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
},
'mobile-large': {
spacing: { '0': 0, xs: 6, sm: 10, md: 14, base: 18, lg: 24, xl: 28, '2xl': 36, '3xl': 44, '4xl': 56 },
borderRadius: { none: 0, sm: 3, base: 6, md: 8, lg: 10, xl: 14, '2xl': 18, full: 9999 },
fontSize: { xs: 11, sm: 13, base: 15, md: 17, lg: 19, xl: 22, '2xl': 26, '3xl': 32, '4xl': 40 },
size: { xs: 20, sm: 28, md: 36, base: 44, lg: 52, xl: 68, '2xl': 84, '3xl': 100 },
"mobile-large": {
spacing: { "0": 0, xs: 6, sm: 10, md: 14, base: 18, lg: 24, xl: 28, "2xl": 36, "3xl": 44, "4xl": 56 },
borderRadius: { none: 0, sm: 3, base: 6, md: 8, lg: 10, xl: 14, "2xl": 18, full: 9999 },
fontSize: { xs: 11, sm: 13, base: 15, md: 17, lg: 19, xl: 22, "2xl": 26, "3xl": 32, "4xl": 40 },
size: { xs: 20, sm: 28, md: 36, base: 44, lg: 52, xl: 68, "2xl": 84, "3xl": 100 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
},
'tablet': {
spacing: { '0': 0, xs: 6, sm: 10, md: 16, base: 20, lg: 24, xl: 32, '2xl': 40, '3xl': 48, '4xl': 64 },
borderRadius: { none: 0, sm: 4, base: 6, md: 8, lg: 12, xl: 16, '2xl': 20, full: 9999 },
fontSize: { xs: 12, sm: 14, base: 16, md: 18, lg: 20, xl: 24, '2xl': 28, '3xl': 36, '4xl': 44 },
size: { xs: 24, sm: 32, md: 40, base: 48, lg: 56, xl: 72, '2xl': 88, '3xl': 104 },
"tablet": {
spacing: { "0": 0, xs: 6, sm: 10, md: 16, base: 20, lg: 24, xl: 32, "2xl": 40, "3xl": 48, "4xl": 64 },
borderRadius: { none: 0, sm: 4, base: 6, md: 8, lg: 12, xl: 16, "2xl": 20, full: 9999 },
fontSize: { xs: 12, sm: 14, base: 16, md: 18, lg: 20, xl: 24, "2xl": 28, "3xl": 36, "4xl": 44 },
size: { xs: 24, sm: 32, md: 40, base: 48, lg: 56, xl: 72, "2xl": 88, "3xl": 104 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
},
'tablet-large': {
spacing: { '0': 0, xs: 8, sm: 12, md: 20, base: 24, lg: 32, xl: 40, '2xl': 48, '3xl': 64, '4xl': 80 },
borderRadius: { none: 0, sm: 6, base: 8, md: 10, lg: 14, xl: 18, '2xl': 24, full: 9999 },
fontSize: { xs: 14, sm: 16, base: 18, md: 20, lg: 24, xl: 28, '2xl': 32, '3xl': 40, '4xl': 48 },
size: { xs: 28, sm: 36, md: 44, base: 52, lg: 64, xl: 80, '2xl': 96, '3xl': 112 },
"tablet-large": {
spacing: { "0": 0, xs: 8, sm: 12, md: 20, base: 24, lg: 32, xl: 40, "2xl": 48, "3xl": 64, "4xl": 80 },
borderRadius: { none: 0, sm: 6, base: 8, md: 10, lg: 14, xl: 18, "2xl": 24, full: 9999 },
fontSize: { xs: 14, sm: 16, base: 18, md: 20, lg: 24, xl: 28, "2xl": 32, "3xl": 40, "4xl": 48 },
size: { xs: 28, sm: 36, md: 44, base: 52, lg: 64, xl: 80, "2xl": 96, "3xl": 112 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
}
}
};
/**
* 加载主题配置
......@@ -91,31 +91,36 @@ function loadThemeConfig(): ThemeConfig {
// 2. 使用 uni.getFileSystemManager() 读取本地文件
// 3. 使用静态 import(如果支持)
return defaultThemeConfig
return defaultThemeConfig;
}
/**
* 根据屏幕尺寸自动选择主题
*/
export function getThemeByScreenSize(): ThemeName {
const screenSize = getScreenSize()
const screenSize = getScreenSize();
switch (screenSize) {
case 'small':
return 'mobile-small'
case 'medium':
return 'mobile-medium'
case 'large':
return 'mobile-large'
case 'xlarge':
case "large": {
return "mobile-large";
}
case "medium": {
return "mobile-medium";
}
case "small": {
return "mobile-small";
}
case "xlarge": {
// 根据屏幕宽度进一步判断是 tablet 还是 tablet-large
const windowInfo = uni.getWindowInfo()
const windowInfo = uni.getWindowInfo();
if (windowInfo.windowWidth >= 1920) {
return 'tablet-large'
return "tablet-large";
}
return 'tablet'
default:
return 'mobile-medium'
return "tablet";
}
default: {
return "mobile-medium";
}
}
}
......@@ -123,66 +128,83 @@ export function getThemeByScreenSize(): ThemeName {
* 主题管理器类
*/
export class ThemeManager {
private themes: ThemeConfig | null = null
private currentThemeName: ThemeName = 'mobile-medium'
private currentThemeName: ThemeName = "mobile-medium";
private themes: null | ThemeConfig = null;
constructor() {
this.themes = loadThemeConfig()
this.currentThemeName = getThemeByScreenSize()
this.themes = loadThemeConfig();
this.currentThemeName = getThemeByScreenSize();
}
/**
* 获取当前主题名称
* 自动选择主题(根据屏幕尺寸)
*/
getCurrentThemeName(): ThemeName {
return this.currentThemeName
autoSelectTheme(): void {
this.currentThemeName = getThemeByScreenSize();
}
/**
* 设置当前主题
* 获取圆角值
*/
setTheme(themeName: ThemeName): boolean {
getBorderRadius(key: string): number {
return this.getValue("borderRadius", key, 0);
}
/**
* 获取当前主题变量
*/
getCurrentTheme(): null | ThemeVariables {
if (this.themes == null) {
console.warn('[theme-manager] Theme config not loaded')
return false
}
if (get(this.themes, themeName) == null) {
console.warn(`[theme-manager] Theme "${themeName}" not found`)
return false
return null;
}
this.currentThemeName = themeName
return true
return get(this.themes, this.currentThemeName) as null | ThemeVariables;
}
/**
* 自动选择主题(根据屏幕尺寸)
* 获取当前主题名称
*/
autoSelectTheme(): void {
this.currentThemeName = getThemeByScreenSize()
getCurrentThemeName(): ThemeName {
return this.currentThemeName;
}
/**
* 获取当前主题变量
* 获取字体大小
*/
getCurrentTheme(): ThemeVariables | null {
if (this.themes == null) {
return null
}
return get(this.themes, this.currentThemeName) as ThemeVariables | null
getFontSize(key: string): number {
return this.getValue("fontSize", key, 14);
}
/**
* 获取行高值
*/
getLineHeight(key: string): number {
return this.getValue("lineHeight", key, 1.5);
}
/**
* 获取尺寸值
*/
getSize(key: string): number {
return this.getValue("size", key, 0);
}
/**
* 获取间距值
*/
getSpacing(key: string): number {
return this.getValue("spacing", key, 0);
}
/**
* 获取指定主题变量
*/
getTheme(themeName: ThemeName): ThemeVariables | null {
getTheme(themeName: ThemeName): null | ThemeVariables {
if (this.themes == null) {
return null
return null;
}
return get(this.themes, themeName) as ThemeVariables | null
return get(this.themes, themeName) as null | ThemeVariables;
}
/**
......@@ -192,69 +214,52 @@ export class ThemeManager {
* @param defaultValue 默认值
*/
getValue(category: string, key: string, defaultValue: number = 0): number {
const theme = this.getCurrentTheme()
const theme = this.getCurrentTheme();
if (theme == null) {
return defaultValue
return defaultValue;
}
const categoryObj = get(theme, category) as any
const categoryObj = get(theme, category) as any;
if (categoryObj == null) {
return defaultValue
return defaultValue;
}
const value = get(categoryObj, key)
if (value == null || typeof value !== 'number') {
return defaultValue
const value = get(categoryObj, key);
if (value == null || typeof value !== "number") {
return defaultValue;
}
return value
}
/**
* 获取间距值
*/
getSpacing(key: string): number {
return this.getValue('spacing', key, 0)
}
/**
* 获取圆角值
*/
getBorderRadius(key: string): number {
return this.getValue('borderRadius', key, 0)
}
/**
* 获取字体大小
*/
getFontSize(key: string): number {
return this.getValue('fontSize', key, 14)
}
/**
* 获取尺寸值
*/
getSize(key: string): number {
return this.getValue('size', key, 0)
return value;
}
/**
* 获取行高值
* 设置当前主题
*/
getLineHeight(key: string): number {
return this.getValue('lineHeight', key, 1.5)
setTheme(themeName: ThemeName): boolean {
if (this.themes == null) {
console.warn("[theme-manager] Theme config not loaded");
return false;
}
if (get(this.themes, themeName) == null) {
console.warn(`[theme-manager] Theme "${themeName}" not found`);
return false;
}
this.currentThemeName = themeName;
return true;
}
}
// 全局主题管理器实例
let globalThemeManager: ThemeManager | null = null
let globalThemeManager: null | ThemeManager = null;
/**
* 获取全局主题管理器实例
*/
export function getThemeManager(): ThemeManager {
if (globalThemeManager == null) {
globalThemeManager = new ThemeManager()
globalThemeManager = new ThemeManager();
}
return globalThemeManager
return globalThemeManager;
}
// utils/theme-variables.uts
// CSS 变量主题系统 - 动态设置 CSS 变量值
import { getThemeManager } from './theme-manager.uts'
import { getThemeManager } from "./theme-manager.uts";
/**
* CSS 变量名称映射
......@@ -10,85 +10,85 @@ import { getThemeManager } from './theme-manager.uts'
*/
const CSS_VARIABLES: Record<string, string> = {
// 间距 (Spacing)
'--p-page': 'base', // p-page 使用 base 间距
'--p-xs': 'xs',
'--p-sm': 'sm',
'--p-md': 'md',
'--p-base': 'base',
'--p-lg': 'lg',
'--p-xl': 'xl',
'--p-2xl': '2xl',
'--p-3xl': '3xl',
'--p-4xl': '4xl',
"--p-page": "base", // p-page 使用 base 间距
"--p-xs": "xs",
"--p-sm": "sm",
"--p-md": "md",
"--p-base": "base",
"--p-lg": "lg",
"--p-xl": "xl",
"--p-2xl": "2xl",
"--p-3xl": "3xl",
"--p-4xl": "4xl",
// 圆角 (Border Radius)
'--r-none': 'none',
'--r-sm': 'sm',
'--r-base': 'base',
'--r-md': 'md',
'--r-lg': 'lg',
'--r-xl': 'xl',
'--r-2xl': '2xl',
'--r-full': 'full',
"--r-none": "none",
"--r-sm": "sm",
"--r-base": "base",
"--r-md": "md",
"--r-lg": "lg",
"--r-xl": "xl",
"--r-2xl": "2xl",
"--r-full": "full",
// 字体大小 (Font Size)
'--t-xs': 'xs',
'--t-sm': 'sm',
'--t-base': 'base',
'--t-md': 'md',
'--t-lg': 'lg',
'--t-xl': 'xl',
'--t-2xl': '2xl',
'--t-3xl': '3xl',
'--t-4xl': '4xl',
"--t-xs": "xs",
"--t-sm": "sm",
"--t-base": "base",
"--t-md": "md",
"--t-lg": "lg",
"--t-xl": "xl",
"--t-2xl": "2xl",
"--t-3xl": "3xl",
"--t-4xl": "4xl",
// 尺寸 (Size)
'--s-xs': 'xs',
'--s-sm': 'sm',
'--s-md': 'md',
'--s-base': 'base',
'--s-lg': 'lg',
'--s-xl': 'xl'
}
"--s-xs": "xs",
"--s-sm": "sm",
"--s-md": "md",
"--s-base": "base",
"--s-lg": "lg",
"--s-xl": "xl"
};
/**
* 设置 CSS 变量到根元素
* 注意:uni-app x 中需要在根 view 上设置 style
*/
export function setThemeVariables(rootElement: any = null): void {
const themeManager = getThemeManager()
const theme = themeManager.getCurrentTheme()
const themeManager = getThemeManager();
const theme = themeManager.getCurrentTheme();
if (theme == null) {
console.warn('[theme-variables] Theme not loaded')
return
console.warn("[theme-variables] Theme not loaded");
return;
}
// 构建 CSS 变量对象
const cssVars: Record<string, string> = {}
const cssVars: Record<string, string> = {};
// 设置间距变量
Object.keys(CSS_VARIABLES).forEach((cssVar) => {
const varName = CSS_VARIABLES[cssVar]
const varName = CSS_VARIABLES[cssVar];
if (cssVar.startsWith('--p-')) {
if (cssVar.startsWith("--p-")) {
// 间距变量
cssVars[cssVar] = themeManager.getSpacing(varName) + 'px'
} else if (cssVar.startsWith('--r-')) {
cssVars[cssVar] = `${themeManager.getSpacing(varName) }px`;
} else if (cssVar.startsWith("--r-")) {
// 圆角变量
cssVars[cssVar] = themeManager.getBorderRadius(varName) + 'px'
} else if (cssVar.startsWith('--t-')) {
cssVars[cssVar] = `${themeManager.getBorderRadius(varName) }px`;
} else if (cssVar.startsWith("--t-")) {
// 字体大小变量
cssVars[cssVar] = themeManager.getFontSize(varName) + 'px'
} else if (cssVar.startsWith('--s-')) {
cssVars[cssVar] = `${themeManager.getFontSize(varName) }px`;
} else if (cssVar.startsWith("--s-")) {
// 尺寸变量
cssVars[cssVar] = themeManager.getSize(varName) + 'px'
cssVars[cssVar] = `${themeManager.getSize(varName) }px`;
}
})
});
// 在 uni-app x 中,需要通过 :style 绑定到根元素
// 这里返回样式对象,供组件使用
return cssVars
return cssVars;
}
/**
......@@ -96,7 +96,7 @@ export function setThemeVariables(rootElement: any = null): void {
* 用于绑定到根元素的 :style
*/
export function getThemeVariablesStyle(): Record<string, string> {
return setThemeVariables()
return setThemeVariables();
}
/**
......
import { join } from "node:path";
import uni from "@dcloudio/vite-plugin-uni";
import tailwindcss from "tailwindcss";
import { defineConfig } from "vite";
// import { cool } from "@cool-vue/vite-plugin";
import { proxy } from "./config/proxy";
import { r } from "./shared.js";
import { join } from "node:path";
import uni from "@dcloudio/vite-plugin-uni";
import tailwindcss from "tailwindcss";
const resolve = (dir: string) => join(__dirname, dir);
//为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api)
// 为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api)
for (const i in proxy) {
proxy[`/${i}/`] = proxy[i];
}
......
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!