修改单位加载方法,加载还有问题。

This commit is contained in:
廖德云 2025-12-09 00:30:56 +08:00
parent bfe9142db2
commit c187d5de51
3 changed files with 697 additions and 583 deletions

View File

@ -29,7 +29,6 @@
<script setup> <script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed, nextTick } from 'vue'; import { ref, watch, onMounted, onBeforeUnmount, computed, nextTick } from 'vue';
import { listConvert } from '@/api/system/convert.js';
// props // props
const props = defineProps({ const props = defineProps({
@ -138,7 +137,9 @@ const popupPosition = computed(() => {
left: `${rect.left + window.scrollX}px` left: `${rect.left + window.scrollX}px`
}; };
}); });
import { useUnitStore } from '@/store/modules/unitData'
const unitStore = useUnitStore()
// //
const safeUpdateWidth = () => { const safeUpdateWidth = () => {
if (unitLabel.value) { if (unitLabel.value) {
@ -203,10 +204,17 @@ const loadUnits = async (unitType) => {
var unitDatalist =JSON.parse( localStorage.getItem("unitData")); var unitDatalist =JSON.parse( localStorage.getItem("unitData"));
if (unitDatalist) {
unitData.value = unitDatalist[unitType]; unitData.value = unitDatalist[unitType];
baseUnit.value = unitData.value.find((u) => u.baseUnit === 'Y'); baseUnit.value = unitData.value.find((u) => u.baseUnit === 'Y');
console.log(baseUnit.value); console.log(baseUnit.value);
}else{
unitStore.restoreUnitDataFromLocal();
await unitStore.getList();
}
// const res = await listConvert({ // const res = await listConvert({
// unitType: unitType, // unitType: unitType,

View File

@ -1,14 +1,43 @@
import { defineStore } from 'pinia'
import { listConvert } from '@/api/system/convert.js' import { listConvert } from '@/api/system/convert.js'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// 定义计量单位Store // 定义计量单位接口
const useUnitStore = defineStore( export interface UnitItem {
'unit', // Store唯一标识 id: number
{ unitType: string
unitName: string
conversionFactor: number
unitOrder: number
baseUnit: string
status: string
unitTypeName: string
}
export interface UnitQueryParams {
pageNum: number
pageSize: number
unitType: string | null
unitName: string | null
baseUnit: string | null
conversionFactor: number | null
unitTypeName: string | null
status: string | null
unitOrder: number | null
}
// 定义按类型分组的单位数据结构
export interface GroupedUnitData {
[unitType: string]: UnitItem[]
}
export const useUnitStore = defineStore('unit', {
state: () => ({ state: () => ({
// 分组后的单位数据按unitType分组 // 单位数据列表
unitData: {}, unitData: [] as UnitItem[],
// 查询参数(与原逻辑一致) // 按类型分组后的单位数据
groupedUnitData: {} as GroupedUnitData,
// 查询参数
queryParams: { queryParams: {
pageNum: 1, pageNum: 1,
pageSize: 1000, pageSize: 1000,
@ -19,20 +48,48 @@ const useUnitStore = defineStore(
unitTypeName: null, unitTypeName: null,
status: null, status: null,
unitOrder: null unitOrder: null
}, } as UnitQueryParams,
// 加载状态(扩展:可选) // 加载状态
loading: false loading: false,
// 总条数
total: 0
}), }),
getters: {
// 获取所有单位类型
unitTypes: (state) => {
return Object.keys(state.groupedUnitData)
},
// 获取特定类型的单位列表
getUnitsByType: (state) => {
return (unitType: string) => {
return state.groupedUnitData[unitType] || []
}
},
// 获取基本单位
getBaseUnit: (state) => {
return (unitType: string) => {
const units = state.groupedUnitData[unitType] || []
return units.find(unit => unit.baseUnit === '1') || units[0]
}
},
// 按类型排序的单位数据
sortedUnitTypes: (state) => {
return Object.keys(state.groupedUnitData).sort()
}
},
actions: { actions: {
/** // 按单位类型分组
* groupByUnitType(data: UnitItem[]): GroupedUnitData {
* @param {Array} data return data.reduce((acc: GroupedUnitData, unit: UnitItem) => {
* @returns {Object} unitType分组后的对象 const type = unit.unitType
*/ if (!acc[type]) {
groupByUnitType(data) { acc[type] = []
return data.reduce((acc, unit) => { }
const type = unit.unitType;
if (!acc[type]) acc[type] = [];
acc[type].push({ acc[type].push({
id: unit.id, id: unit.id,
unitType: unit.unitType, unitType: unit.unitType,
@ -42,43 +99,19 @@ const useUnitStore = defineStore(
baseUnit: unit.baseUnit, baseUnit: unit.baseUnit,
status: unit.status, status: unit.status,
unitTypeName: unit.unitTypeName unitTypeName: unit.unitTypeName
}); })
return acc; // 按单位排序
}, {}); acc[type].sort((a, b) => (a.unitOrder || 0) - (b.unitOrder || 0))
return acc
}, {})
}, },
/** // 设置查询参数
* setQueryParams(params: Partial<UnitQueryParams>) {
* @returns {Promise} Promise this.queryParams = { ...this.queryParams, ...params }
*/
getList() {
// 标记加载中
this.loading = true;
return new Promise((resolve, reject) => {
listConvert(this.queryParams)
.then((response) => {
// 数据分组处理
const unitDataGrouped = this.groupByUnitType(response.rows);
// 更新Store状态
this.unitData = unitDataGrouped;
// 本地存储备份
localStorage.setItem('unitData', JSON.stringify(unitDataGrouped));
resolve(unitDataGrouped);
})
.catch((error) => {
console.error('获取单位数据失败:', error);
reject(error);
})
.finally(() => {
// 结束加载状态
this.loading = false;
});
});
}, },
/** // 重置查询参数
* 便
*/
resetQueryParams() { resetQueryParams() {
this.queryParams = { this.queryParams = {
pageNum: 1, pageNum: 1,
@ -90,30 +123,94 @@ const useUnitStore = defineStore(
unitTypeName: null, unitTypeName: null,
status: null, status: null,
unitOrder: null unitOrder: null
}; }
}, },
/** // 获取单位列表
* async getList() {
* @returns {Promise} Promise this.loading = true
*/ try {
refreshUnitData() { const response = await listConvert(this.queryParams)
// 重置页码后重新获取 this.unitData = response.rows || []
this.queryParams.pageNum = 1; this.total = response.total || 0
return this.getList(); this.groupedUnitData = this.groupByUnitType(this.unitData)
// 保存到localStorage
localStorage.setItem('unitData', JSON.stringify(this.groupedUnitData))
return response
} catch (error) {
console.error('获取单位数据失败:', error)
throw error
} finally {
this.loading = false
}
}, },
/** // 从localStorage加载缓存的单位数据
* loadFromLocalStorage() {
*/ try {
restoreUnitDataFromLocal() { const storedData = localStorage.getItem('unitData')
const localData = localStorage.getItem('unitData'); if (storedData) {
if (localData) { this.groupedUnitData = JSON.parse(storedData)
this.unitData = JSON.parse(localData); // 从分组数据中提取所有单位
this.unitData = Object.values(this.groupedUnitData).flat()
return true
} }
} catch (error) {
console.error('从localStorage加载单位数据失败:', error)
} }
} return false
} },
);
export default useUnitStore; // 清除localStorage中的单位数据
clearLocalStorage() {
localStorage.removeItem('unitData')
},
// 单位转换方法
convertUnit(value: number, fromUnit: UnitItem, toUnit: UnitItem): number {
if (fromUnit.unitType !== toUnit.unitType) {
throw new Error('单位类型不匹配,无法转换')
}
// 先转换到基本单位,再从基本单位转换到目标单位
const valueInBaseUnit = value * (fromUnit.conversionFactor || 1)
return valueInBaseUnit / (toUnit.conversionFactor || 1)
},
// 根据单位名称查找单位
findUnitByName(unitName: string): UnitItem | undefined {
return this.unitData.find(unit => unit.unitName === unitName)
},
// 根据ID查找单位
findUnitById(id: number): UnitItem | undefined {
return this.unitData.find(unit => unit.id === id)
},
// 刷新单位数据
async refresh() {
await this.getList()
},
// 获取有效的单位列表(状态为正常的)
getActiveUnits(unitType?: string): UnitItem[] {
const units = unitType
? (this.groupedUnitData[unitType] || [])
: this.unitData
return units.filter(unit => unit.status === '0') // 假设 '0' 表示正常状态
},
// 根据类型和名称模糊查询单位
searchUnits(type: string, keyword: string): UnitItem[] {
const units = this.groupedUnitData[type] || []
return units.filter(unit =>
unit.unitName.includes(keyword) ||
(unit.unitTypeName && unit.unitTypeName.includes(keyword))
)
}
}
})
export default useUnitStore

View File

@ -15,7 +15,8 @@
<div class="stat-value text-ellipsis" :title="formatDate(userInfo.loginDate) || '暂无'"> <div class="stat-value text-ellipsis" :title="formatDate(userInfo.loginDate) || '暂无'">
上次登录 {{ formatDate(userInfo.loginDate) || '暂无' }} 上次登录 {{ formatDate(userInfo.loginDate) || '暂无' }}
</div> </div>
</div></div> </div>
</div>
<div class="user-stats"> <div class="user-stats">
<div class="stat-item"> <div class="stat-item">
<div class="stat-value text-ellipsis" :title="userInfo.deptName || '暂无'"> <div class="stat-value text-ellipsis" :title="userInfo.deptName || '暂无'">
@ -44,7 +45,8 @@
</div> </div>
</template> </template>
<div v-if="noticeList.length" class="notice-list"> <div v-if="noticeList.length" class="notice-list">
<div v-for="item in noticeList" :key="item.noticeId" class="notice-item" @click="showNoticeDetail(item)"> <div v-for="item in noticeList" :key="item.noticeId" class="notice-item"
@click="showNoticeDetail(item)">
<el-tag size="small" :type="item.noticeType === '1' ? 'danger' : 'success'"> <el-tag size="small" :type="item.noticeType === '1' ? 'danger' : 'success'">
{{ item.noticeType === '1' ? '通知' : '公告' }} {{ item.noticeType === '1' ? '通知' : '公告' }}
</el-tag> </el-tag>
@ -68,7 +70,8 @@
</div> </div>
<el-row :gutter="20" class="feature-section"> <el-row :gutter="20" class="feature-section">
<el-col :lg="8" :md="12" :sm="24" :xs="24" v-for="(feature, index) in features" :key="index"> <el-col :lg="8" :md="12" :sm="24" :xs="24" v-for="(feature, index) in features"
:key="index">
<div class="feature-item"> <div class="feature-item">
<div class="feature-icon"> <div class="feature-icon">
<el-icon> <el-icon>
@ -152,7 +155,7 @@
</div> </div>
</template> </template>
<script setup name="Index" lang="ts"> <script setup name="Index" lang="ts">
import { ref, onMounted } from 'vue' import { ref, onMounted, onShow } from 'vue'
import { listNotice } from '@/api/system/notice' import { listNotice } from '@/api/system/notice'
import { parseTime } from '@/utils/ruoyi' import { parseTime } from '@/utils/ruoyi'
import { Bell, ArrowRight } from '@element-plus/icons-vue' import { Bell, ArrowRight } from '@element-plus/icons-vue'
@ -162,7 +165,9 @@ import useUserStore from '@/store/modules/user'
import { useRouter, type RouteLocationRaw } from 'vue-router' import { useRouter, type RouteLocationRaw } from 'vue-router'
import { GeekResponseForList } from '@/types/request' import { GeekResponseForList } from '@/types/request'
import { useUnitStore } from '@/store/modules/unitData'
const unitStore = useUnitStore()
const router = useRouter() const router = useRouter()
@ -280,11 +285,15 @@ const viewMoreNotices = () => {
router.push(route) router.push(route)
} }
onMounted(() => { onMounted(async () => {
userInfo.getInfo() userInfo.getInfo()
getNoticeList() await getNoticeList()
//
await unitStore.getList();
}) })
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">