修改单位存储,获取错误,微信小程序发布成功

This commit is contained in:
廖德云 2025-12-19 00:53:04 +08:00
parent 4d837466d0
commit 33847fef1c
11 changed files with 731 additions and 611 deletions

View File

@ -4,9 +4,7 @@ import request from '@/utils/request'
export function listConvert(query) {
return request({
url: '/system/convert/list',
headers: {
isToken: false
},
method: 'get',
params: query
})
@ -16,9 +14,7 @@ export function listConvert(query) {
export function getConvert(id) {
return request({
url: '/system/convert/' + id,
headers: {
isToken: false
},
method: 'get'
})
}
@ -27,9 +23,7 @@ export function getConvert(id) {
export function addConvert(data) {
return request({
url: '/system/convert',
headers: {
isToken: false
},
method: 'post',
data: data
})
@ -39,9 +33,7 @@ export function addConvert(data) {
export function updateConvert(data) {
return request({
url: '/system/convert',
headers: {
isToken: false
},
method: 'put',
data: data
})
@ -51,9 +43,7 @@ export function updateConvert(data) {
export function delConvert(id) {
return request({
url: '/system/convert/' + id,
headers: {
isToken: false
},
method: 'delete'
})
}

View File

@ -1,7 +1,6 @@
import App from './App.vue'
import plugins from './plugins'
import store from './store'
import uviewPlus from 'uview-plus'
import { createSSRApp } from 'vue'
@ -15,7 +14,6 @@ import { parseTime, resetForm, addDateRange, handleTree, selectDictLabel, select
export function createApp() {
const app = createSSRApp(App)
app.use(store)
app.use(uviewPlus)
app.use(plugins)
// #ifndef MP-WEIXIN

View File

@ -16,6 +16,9 @@
"autoclose" : true,
"delay" : 0
},
"compatible" : {
"ignoreVersion" : true //
},
/* */
"modules" : {
"OAuth" : {}

View File

@ -34,15 +34,21 @@
onMounted
} from "vue";
import modal from "@/plugins/modal"
import {
storage
} from '@/utils/storageUnit.ts';
import {
extractModuleData
} from '@/utils/moudlesData.ts';
import useUnitStore from '@/store/modules/unitData.ts';
import {
getToken,
setToken,
removeToken
} from "@/utils/auth";
const unitStore = useUnitStore();
const current = ref(0);
const swiperDotIndex = ref(0);
const data = ref([{
@ -59,13 +65,59 @@
//
const moudlesGroups = ref([]);
//
const checkLoginStatus = () => {
// 1. token
const token = getToken();
console.log(token)
// 2. token/
if (!token) {
uni.reLaunch({
url: '/pages/login'
});
return false; //
}
return true; //
};
onMounted(async () => {
//
const isLogin = checkLoginStatus();
if (!isLogin) return; //
moudlesGroups.value = extractModuleData(['流量计算', '参数计算'], false)
//
unitStore.restoreUnitDataFromLocal();
try {
await unitStore.getList();
} catch (error) {
console.error('获取单位数据失败:', error);
})
if (error.code === 401 ||
(error.message &&
(error.message.includes('会话过期') ||
error.message.includes('无效的会话')))) {
//
uni.removeStorageSync('token');
uni.removeStorageSync('userInfo');
//
uni.reLaunch({
url: '/pages/login/'
});
} else {
//
const errorMsg = error.message || '数据加载失败,请稍后重试';
modal.showToast({
title: errorMsg,
mask: false,
icon: 'none',
duration: 2000
});
}
}
});
function navigateToMoudles(item) {
console.log(item)

View File

@ -130,12 +130,17 @@
wxLogin,
wxAppLogin
} from '@/api/oauth'
import useUserStore from '@/store/modules/user'
import {
setToken
} from '@/utils/auth'
import config from '@/config.js'
import request from '@/utils/request'
//
let isChecking = false;
let hasChecked = false;
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const appName = config.appInfo.name || '天然气工具箱'
@ -245,13 +250,18 @@
const res = await login(params.username, params.password, params.code, params.uuid)
if (res.token) {
setToken(res.token)
await userStore.getInfo()
uni.switchTab({
url: '/pages/index'
});
//
setTimeout(() => {
// 使 reLaunch
uni.reLaunch({
url: '/pages/index'
})
}, 300)
}
} catch (error) {
//
@ -405,15 +415,55 @@
getCaptcha()
})
onLoad(() => {
// token
const token = uni.getStorageSync('token')
if (token) {
onLoad(async (options) => {
// === ===
if (isChecking || hasChecked) return;
isChecking = true;
try {
const token = uni.getStorageSync('token');
if (!token) {
hasChecked = true;
isChecking = false;
getCaptcha(); //
return;
}
//
if (options?.skipAutoLogin === 'true') {
hasChecked = true;
isChecking = false;
return;
}
// token 使
try {
await userStore.getInfo(); //
//
uni.reLaunch({
url: '/pages/index'
})
});
} catch (error) {
// === token ===
if (error.code === 401 ||
(error.message &&
(error.message.includes('会话过期') ||
error.message.includes('无效的会话')))) {
// token
uni.removeStorageSync('token');
uni.removeStorageSync('userInfo');
modal.alert('登录已过期,请重新登录');
}
})
getCaptcha(); //
}
} finally {
isChecking = false;
hasChecked = true;
}
});
</script>
<style scoped>

View File

@ -1,18 +1,17 @@
<script setup lang="ts">
import logo from 'https://ngtools.cn:3000/static/logo.png';
</script>
<template>
<view class="taobao">
<view class="title">
<view class="left">
<image class="buddha" :src="logo" mode="aspectFill"></image>
<image class="buddha" src="https://ngtools.cn:3000/static/logo.png" mode="aspectFill"></image>
<view class="store">袜子精保护协会</view>
</view>
<view class="entrance">进店</view>
</view>
<view class="ticket">
<view class="left">
<image class="picture" :src="logo" mode="widthFix"></image>
<image class="picture" src="https://ngtools.cn:3000/static/logo.png" mode="widthFix"></image>
<view class="introduce">
<view class="top">

View File

@ -133,32 +133,6 @@ export const useUnitStore = defineStore('unit', {
}
},
// 处理API错误
handleApiError(error: any) {
console.error('API请求错误:', error)
this.error = error.message || '请求失败'
// 如果是403错误可能是未登录或权限不足
if (error.statusCode === 403 || error.errMsg?.includes('403')) {
console.warn('获取单位数据失败,可能是未登录或权限不足')
this.error = '未登录或权限不足,将使用默认单位数据'
// 检查是否已登录
try {
const token = uni.getStorageSync('token')
if (!token) {
console.log('用户未登录')
}
} catch (e) {
console.warn('检查登录状态失败:', e)
}
}
},
// 获取单位列表 - 兼容多平台,带错误处理
async getList() {
this.loading = true
@ -177,7 +151,8 @@ export const useUnitStore = defineStore('unit', {
console.log('单位数据获取成功,类型数量:', Object.keys(this.groupedUnitData).length)
return response
} catch (error) {
this.handleApiError(error)
this.error = error instanceof Error ? error.message : '获取单位数据失败'
console.error('获取单位数据出错:', error)
throw error
} finally {
this.loading = false
@ -194,76 +169,77 @@ export const useUnitStore = defineStore('unit', {
console.log('使用现有单位数据')
return { rows: this.unitData, total: this.unitData.length }
}
// 尝试从缓存加载
const cachedData = this.loadFromStorage()
if (cachedData && Object.keys(cachedData).length > 0) {
console.log('使用缓存中的单位数据')
return { rows: this.unitData, total: this.unitData.length }
}
return { rows: [], total: 0 }
}
},
// 从存储加载缓存的单位数据 - 兼容多平台
loadFromStorage() {
loadFromStorage(): GroupedUnitData | false {
try {
let storedData = null
// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-LARK || MP-KUAISHOU
// 微信小程序等平台使用uni.getStorageSync
// 统一使用uni API作为基础跨平台兼容
try {
storedData = uni.getStorageSync('unitData')
// #endif
// #ifdef APP-PLUS || H5
// App和H5平台使用localStorage
} catch (e) {
// 备用方案H5/localStorage
if (typeof localStorage !== 'undefined') {
storedData = localStorage.getItem('unitData')
}
// #endif
// #ifdef HARMONY
// 鸿蒙平台使用鸿蒙API这里需要根据鸿蒙API调整
// 暂时使用uni.getStorageSync作为备选
try {
storedData = uni.getStorageSync('unitData')
} catch (e) {
console.warn('鸿蒙平台存储获取失败:', e)
}
// #endif
if (storedData) {
this.groupedUnitData = JSON.parse(storedData)
if (!storedData) {
console.log('无缓存的单位数据')
return false // 明确返回false避免undefined
}
// 处理JSON字符串和对象两种情况
const parsedData = typeof storedData === 'string'
? JSON.parse(storedData)
: storedData
// 验证数据结构
if (typeof parsedData !== 'object' || parsedData === null) {
console.warn('缓存的单位数据格式无效')
return false
}
this.groupedUnitData = parsedData
// 从分组数据中提取所有单位
this.unitData = Object.values(this.groupedUnitData).flat()
return true
}
console.log('从缓存加载单位数据成功,类型数:', Object.keys(this.groupedUnitData).length)
return this.groupedUnitData
} catch (error) {
console.error('从存储加载单位数据失败:', error)
return false // 明确返回false
}
return false
},
// 保存单位数据到存储 - 兼容多平台
saveUnitDataToStorage() {
saveUnitDataToStorage(): boolean {
try {
const dataStr = JSON.stringify(this.groupedUnitData)
// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-LARK || MP-KUAISHOU
// 微信小程序等平台使用uni.setStorageSync
uni.setStorageSync('unitData', dataStr)
// #endif
// #ifdef APP-PLUS || H5
// App和H5平台使用localStorage
if (typeof localStorage !== 'undefined') {
localStorage.setItem('unitData', dataStr)
}
// #endif
// #ifdef HARMONY
// 鸿蒙平台使用鸿蒙API这里需要根据鸿蒙API调整
// 暂时使用uni.setStorageSync作为备选
// 优先使用uni API
try {
uni.setStorageSync('unitData', dataStr)
} catch (e) {
console.warn('鸿蒙平台存储保存失败:', e)
// 备用方案H5/localStorage
if (typeof localStorage !== 'undefined') {
localStorage.setItem('unitData', dataStr)
} else {
throw e
}
}
// #endif
console.log('单位数据已保存到缓存')
return true
} catch (error) {
console.error('保存单位数据到存储失败:', error)
@ -272,29 +248,19 @@ export const useUnitStore = defineStore('unit', {
},
// 清除存储中的单位数据 - 兼容多平台
clearStorage() {
clearStorage(): boolean {
try {
// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-LARK || MP-KUAISHOU
// 微信小程序等平台使用uni.removeStorageSync
uni.removeStorageSync('unitData')
// #endif
// #ifdef APP-PLUS || H5
// App和H5平台使用localStorage
if (typeof localStorage !== 'undefined') {
localStorage.removeItem('unitData')
}
// #endif
// #ifdef HARMONY
// 鸿蒙平台使用鸿蒙API这里需要根据鸿蒙API调整
// 暂时使用uni.removeStorageSync作为备选
// 优先使用uni API
try {
uni.removeStorageSync('unitData')
} catch (e) {
console.warn('鸿蒙平台存储清除失败:', e)
// 备用方案H5/localStorage
if (typeof localStorage !== 'undefined') {
localStorage.removeItem('unitData')
} else {
throw e
}
}
// #endif
return true
} catch (error) {
@ -359,10 +325,6 @@ export const useUnitStore = defineStore('unit', {
return this.loadFromStorage()
},
// 清除错误
clearError() {
this.error = null

View File

@ -1,63 +1,36 @@
<template>
<view class="a-yjly-inputunit" :style="{ width: width + 'px' }">
<!-- 数值输入框 -->
<input
v-model.number="inputValue"
class="input-field"
type="number"
:ref="'inputRef'"
:style="{
<input v-model.number="inputValue" class="input-field" type="number" :ref="'inputRef'" :style="{
width: inputWidth + 'px',
height: height + 'px',
lineHeight: height + 'px'
}"
@input="handleInputChange"
/>
}" @input="handleInputChange" />
<!-- 单位标签 -->
<view
v-if="enableConvert"
:ref="'unitLabel'"
class="unit-label"
:style="{
<view v-if="enableConvert" :ref="'unitLabel'" class="unit-label" :style="{
color: 'blue',
height: height + 'px',
lineHeight: height + 'px'
}"
@tap="cycleUnit"
@longpress="handleLongPress"
>
}" @tap="cycleUnit" @longpress="handleLongPress">
{{ textUnitName }}
</view>
<view
v-else
class="unit-label"
:style="{
<view v-else class="unit-label" :style="{
color: 'blue',
height: height + 'px',
lineHeight: height + 'px'
}"
>
}">
{{ textUnitName }}
</view>
<!-- 单位选择弹出窗口 -->
<view
v-if="showUnitSelector"
class="unit-selector"
:style="{
<view v-if="showUnitSelector" class="unit-selector" :style="{
left: unitSelectorLeft + 'px',
top: unitSelectorTop + 'px'
}"
>
}">
<scroll-view scroll-y :style="{ maxHeight: '300px' }">
<view
v-for="(unit, index) in sortedUnits"
:key="unit.id"
class="unit-option"
:class="{ active: activeIndex === index }"
@tap="selectUnitHandler(unit, index)"
>
<view v-for="(unit, index) in sortedUnits" :key="unit.id" class="unit-option"
:class="{ active: activeIndex === index }" @tap="selectUnitHandler(unit, index)">
{{ showEnglishOnly ? unit.unitName.split('(')[0] : unit.unitName }}
</view>
</scroll-view>
@ -66,7 +39,9 @@
</template>
<script>
import { storage } from '@/utils/storageUnit.ts';
import useUnitStore from '@/store/modules/unitData.ts';
export default {
name: 'UniUnitConverter',
@ -201,19 +176,28 @@ export default {
try {
let tempData = null;
tempData = storage.getItem('unitData');
let unitStore = useUnitStore();
tempData = unitStore.loadFromStorage();
console.log('从存储获取的数据:', tempData);
// 2.
if (!tempData || !tempData[unitType]) {
console.log('缓存无对应类型数据,从接口获取');
await unitStore.safeGetList();
tempData = unitStore.groupedUnitData;
}
// 3.
this.unitData = tempData[unitType] || [];
if (this.unitData.length === 0) {
console.warn(`未找到${unitType}类型的单位数据`);
return;
}
this.unitData = tempData[unitType];
if (!this.unitData || this.unitData.length === 0) {
return;
}
this.baseUnit = this.unitData.find((u) => u.baseUnit === 'Y');
// 4. baseUnit'1''Y'
this.baseUnit = this.unitData.find((u) => u.baseUnit === 'Y' || u.baseUnit === '1') || this
.unitData[0];
} catch (e) {
console.error('单位数据加载失败:', e);

View File

@ -1,13 +1,78 @@
const TokenKey = 'App-Token'
/**
* Token
* @returns string Token
*/
export function getToken(): string {
return uni.getStorageSync(TokenKey)
try {
// 优先使用uniapp API
const token = uni.getStorageSync(TokenKey)
// 处理非字符串场景如存入了null/undefined
return token ? String(token) : ''
} catch (error) {
// 兼容H5隐私模式/localStorage不可用场景
console.warn('获取Token失败:', error)
return ''
}
}
export function setToken(token:string) {
return uni.setStorageSync(TokenKey, token)
/**
* Token
* @param token
* @returns boolean
*/
export function setToken(token: string): boolean {
try {
if (typeof token !== 'string') {
console.warn('Token必须为字符串已自动转换')
token = String(token)
}
uni.setStorageSync(TokenKey, token)
return true
} catch (error) {
console.error('设置Token失败:', error)
// H5兜底尝试直接操作localStorage
if (process.env.VUE_APP_PLATFORM === 'h5' && typeof localStorage !== 'undefined') {
try {
localStorage.setItem(TokenKey, token)
return true
} catch (e) {
console.error('H5 localStorage设置失败:', e)
}
}
return false
}
}
export function removeToken() {
return uni.removeStorageSync(TokenKey)
/**
* Token
* @returns boolean
*/
export function removeToken(): boolean {
try {
uni.removeStorageSync(TokenKey)
return true
} catch (error) {
console.error('移除Token失败:', error)
// H5兜底
if (process.env.VUE_APP_PLATFORM === 'h5' && typeof localStorage !== 'undefined') {
try {
localStorage.removeItem(TokenKey)
return true
} catch (e) {
console.error('H5 localStorage移除失败:', e)
}
}
return false
}
}
/**
* Token是否有效
* @returns boolean
*/
export function hasValidToken(): boolean {
const token = getToken()
return !!token && token.trim() !== ''
}

View File

@ -63,37 +63,35 @@ const request = <T>(config: RequestConfig): Promise<ResponseData<T>> => {
// === 修复这里的问题 ===
let message = '网络请求失败'
// 安全地获取错误信息
if (error) {
// 小程序环境错误对象可能有不同的结构
if (error.errMsg) {
message = error.errMsg
} else if (error.message) {
message = error.message
// === 重点修复:安全提取错误信息 ===
if (error && typeof error === 'object') {
// 优先使用后端返回的错误消息
if (error.data?.msg) message = error.data.msg;
// 小程序特有的错误结构
else if (error.errMsg) message = error.errMsg;
// 常规错误消息
else if (error.message) message = error.message;
} else if (typeof error === 'string') {
message = error
}
message = error;
}
// 安全地使用 includes 方法 - 添加类型检查
if (message && typeof message === 'string') {
// 特殊错误处理
if (message.includes('Network Error')) {
message = '后端接口连接异常'
message = '网络连接异常';
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
} else {
// 如果 message 不是字符串,转换为字符串
message = String(message || '未知错误')
}
toast(message)
reject(error)
})
})
message = '请求超时,请检查网络';
}
toast(message);
// === 关键返回带code的错误对象 ===
const err = new Error(message);
err.code = error.statusCode || 500; // 保留HTTP状态码
reject(err);
})
})
}
export function postAction(url : string, data ?: any, isToken : boolean = true) {
return request({ data, url, method: 'POST', headers: { isToken }, })
}

View File

@ -26,3 +26,22 @@ export default defineConfig(() => {
}
}
})
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'async', // 仅异步代码抽离
minSize: 20000, // 大于20KB才抽离
cacheGroups: {
commons: {
name: 'commons',
chunks: 'initial',
minChunks: 2, // 被引用2次以上抽离
priority: -10
}
}
}
}
}
}