【elementUI】时间组件传入控制台的值的格式与前端页面显示的不同

文章讲述了在使用Element-UI的日期时间选择器时,前端显示的yyyy-MM-ddhh:mm:ss格式与打印到控制台的带有时区格式不同。解决方法是在组件上添加value-format属性来指定绑定值的格式,确保前后端时间显示一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

使用element-ui的image.png组件时,选择后的时间显示在前端的格式是’yyyy-MM-dd hh:mm:ss’image.png,而传入打印在控制台的格式是带有时区的在这里插入图片描述

解决前的代码:

<el-date-picker
    v-model="startTime"
    class="ml-5"
    type="datetime"
    placeholder="选择开始时间">
</el-date-picker>
<el-date-picker
    v-model="endTime"
    class="ml-5"
    type="datetime"
    placeholder="选择结束时间">
</el-date-picker>

结果:
在这里插入图片描述
在这里插入图片描述

解决方法:添加一个在时间选择器上添加一个可以绑定值的格式的属性 value-format

image.png
日期格式(转自elementui官方文档):
使用format指定输入框的格式;使用value-format指定绑定值的格式。
默认情况下,组件接受并返回Date对象。以下为可用的格式化字符串,以 UTC 2017年1月2日 03:04:05 为例:

格式含义备注举例
yyyy2017
M不补01
MM01
W仅周选择器的 format 可用;不补01
WW仅周选择器的 format 可用01
d不补02
dd02
H小时24小时制;不补03
HH小时24小时制03
h小时12小时制,须和 A 或 a 使用;不补03
hh小时12小时制,须和 A 或 a 使用03
m分钟不补04
mm分钟04
s不补05
ss05
AAM/PM仅 format 可用,大写AM
aam/pm仅 format 可用,小写am
timestampJS时间戳仅 value-format 可用;组件绑定值为number类型1483326245000
[MM]不需要格式化字符使用方括号标识不需要格式化的字符 (如 [A] [MM])MM
<el-date-picker
    v-model="startTime"
    class="ml-5"
    type="datetime"
    placeholder="选择开始时间"
    value-format="yyyy-MM-dd hh:mm:ss">
</el-date-picker>
<el-date-picker
    v-model="endTime"
    class="ml-5"
    type="datetime"
    placeholder="选择结束时间"
    value-format="yyyy-MM-dd hh:mm:ss" >
</el-date-picker>

结果:
前端展示格式如下图:
image.png
控制台展示格式如下图:
在这里插入图片描述

我用的是node10版本的 下面是我的列表页面和详情页面的代码,有一些问题,需要你解决 1.列表前端代码 /** * 设备管理-设备台账页面 * * @author gucw * @date 2025-06-06 */ <template> <div class="mod-config padding"> <el-form :inline="true" :model="dataForm" ref="form" @keyup.enter.native="getDataList()" > <el-form-item label="设备编码" prop="equipmentCode" class="serach-form-item" > <el-input clearable v-model="dataForm.equipmentCode" placeholder="请输入设备编码" ></el-input> </el-form-item> <el-form-item label="设备大类" prop="equipmentCategory"> <el-select clearable v-model="dataForm.equipmentCategory" :placeholder="'请选择设备大类'" > <el-option v-for="(item, index) in equipment_category" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item label="设备小类" prop="equipmentSubcategory"> <el-select clearable v-model="dataForm.equipmentSubcategory" :placeholder="'请选择设备小类'" > <el-option v-for="(item, index) in equipment_subcategory" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item label="归属类型" prop="ownershipType"> <el-select clearable v-model="dataForm.ownershipType" :placeholder="'请选择归属类型'" > <el-option v-for="(item, index) in ownership_type" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item label="设备归属方" prop="equipmentOwner" class="serach-form-item" > <el-input clearable v-model="dataForm.equipmentOwner" placeholder="请输入设备归属方" ></el-input> </el-form-item> <el-form-item label="存放位置" prop="storageLocation" class="serach-form-item" > <el-input clearable v-model="dataForm.storageLocation" placeholder="请输入存放位置" ></el-input> </el-form-item> <el-form-item label="最后检定日期"> <el-date-picker v-model="lastVerificationDateList" type="daterange" range-separator="-" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder=" 结束日期" style="width: 100%" ></el-date-picker> </el-form-item> <el-form-item label="设备状态" prop="equipmentStatus"> <el-select clearable v-model="dataForm.equipmentStatus" :placeholder="'请选择设备状态'" > <el-option v-for="(item, index) in equipment_status" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item label="仓储状态" prop="storageStatus"> <el-select clearable v-model="dataForm.storageStatus" :placeholder="'请选择仓储状态'" > <el-option v-for="(item, index) in storage_status" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item label="检测状态" prop="inspectionStatus"> <el-select clearable v-model="dataForm.inspectionStatus" :placeholder="'请选择检测状态'" > <el-option v-for="(item, index) in inspection_status" :key="item.cId" :label="item.entryname" :value="item.entrycode" ></el-option> </el-select> </el-form-item> <el-form-item> <el-button v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:list')" @click="getDataList()" type="primary" >查询</el-button > <el-button v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:list')" @click="resetForm('form')" >重置</el-button > <el-button v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:add')" type="primary" @click="addOrUpdateHandle()" >新增</el-button > <el-button v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:remove')" type="danger" @click="deleteHandle()" >批量删除</el-button > </el-form-item> </el-form> <EproTable class="m-t-10" :tableData="dataList" :titleData="titleForm" :optionData="optionData" :disselected="false" @tableSelect="getTableSelect" v-loading="tableLoading" > <el-table-column slot="action" fixed="right" label="操作" align="center" width="110" > <template slot-scope="scope"> <el-tooltip content="查看详情" placement="top"> <div class="iconfont icon-chakan click iconStyle pifu" @click.stop="showDetailHandle(scope.row)" ></div> </el-tooltip> <el-tooltip content="编辑" placement="top" v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:edit')" > <div class="iconfont icon-edit click iconStyle pifu" @click.stop="addOrUpdateHandle(scope.row)" ></div> </el-tooltip> <el-tooltip content="删除" placement="top" v-if="isAuth('cmmsEquipmentInfo:cmmsEquipmentInfo:remove')" > <div class="iconfont icon-delete click iconStyle pifu" @click.stop="deleteHandle(scope.row.id)" ></div> </el-tooltip> </template> </el-table-column> </EproTable> <el-pagination background @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalCount" layout="total, sizes, prev, pager, next, jumper" > </el-pagination> <!-- 弹窗, 新增 / 修改 --> <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList" ></add-or-update> <detail ref="detail" @closed="handleDetailClosed"></detail> </div> </template> <script> import AddOrUpdate from "./cmmsEquipmentInfoAddAndUpdate"; import { listCmmsEquipmentInfo, delCmmsEquipmentInfo, } from "@/api/cmmsEquipmentInfo/cmmsEquipmentInfo.js"; import EproTable from "@/components/epro-table/epro-table"; import { getDictionaries } from "@/utils"; import Detail from "./cmmsEquipmentInfoDetail"; export default { data() { return { dataList: [], pageIndex: 1, pageSize: 10, totalCount: 0, tableLoading: false, dataListSelections: [], addOrUpdateVisible: false, equipment_category: [], equipment_subcategory: [], accuracy_level: [], ownership_type: [], purchaseDateList: [], lastVerificationDateList: [], equipment_status: [], storage_status: [], inspection_status: [], optionData: { equipmentCode: { width: "150px" }, equipmentCategoryDict: { width: "150px" }, equipmentSubcategoryDict: { width: "150px" }, ownershipTypeDict: { width: "150px" }, equipmentOwner: { width: "150px" }, purchaseDate: { width: "150px" }, lastVerificationDate: { width: "150px" }, equipmentStatusDict: { width: "150px" }, storageStatusDict: { width: "150px" }, inspectionStatusDict: { width: "150px" }, }, titleForm: { equipmentCode: "设备编码", equipmentCategoryDict: "设备大类", equipmentSubcategoryDict: "设备小类", ownershipTypeDict: "归属类型", equipmentOwner: "设备归属方", purchaseDate: "采购日期", lastVerificationDate: "最后检定日期", equipmentStatusDict: "设备状态", storageStatusDict: "仓储状态", inspectionStatusDict: "检测状态", }, dataForm: { id: null, equipmentCode: null, equipmentCategory: null, equipmentSubcategory: null, ownershipType: null, equipmentOwner: null, purchaseDate: null, storageLocation: null, lastVerificationDate: null, equipmentStatus: null, storageStatus: null, inspectionStatus: null, }, }; }, components: { AddOrUpdate, EproTable, Detail, }, async activated() { await this.getDictionaries(); this.getDataList(); }, methods: { // 获取table数据 getTableSelect(val) { this.dataListSelections = val; }, // 查看详情方法 showDetailHandle(row) { this.$nextTick(() => { this.$refs.detail.init(row); }); }, // 优化后的获取数据方法 async getDataList() { this.$set(this.dataForm, "page", this.pageIndex); this.$set(this.dataForm, "limit", this.pageSize); this.setDateRangeParams(); this.tableLoading = true; try { const { data } = await listCmmsEquipmentInfo(this.dataForm); this.dataList = this.transformDictValues(data.page.list); this.totalCount = data.page.totalCount; } catch (error) { console.error("获取数据失败:", error); } finally { this.tableLoading = false; } }, // 设置日期范围参数 setDateRangeParams() { this.$set( this.dataForm, "beginpurchaseDate", this.purchaseDateList[0] || null ); this.$set( this.dataForm, "endpurchaseDate", this.purchaseDateList[1] || null ); this.$set( this.dataForm, "beginlastVerificationDate", this.lastVerificationDateList[0] || null ); this.$set( this.dataForm, "endlastVerificationDate", this.lastVerificationDateList[1] || null ); }, // 获取字典 getDictionaries() { return new Promise((resolve) => { let arr = [ "equipment_category", "equipment_subcategory", "accuracy_level", "ownership_type", "equipment_status", "storage_status", "inspection_status", "model_description", "specification_model", ]; getDictionaries(arr).then((data) => { this.equipment_category = data["equipment_category"]; this.equipment_subcategory = data["equipment_subcategory"]; this.accuracy_level = data["accuracy_level"]; this.ownership_type = data["ownership_type"]; this.equipment_status = data["equipment_status"]; this.storage_status = data["storage_status"]; this.inspection_status = data["inspection_status"]; this.model_description = data["model_description"]; this.specification_model = data["specification_model"]; resolve(); }); }); }, handleDetailClosed() { // 这里可以添加关闭后的处理逻辑 }, // 新增方法:转换字典 transformDictValues(list) { return list.map((item) => { return { ...item, equipmentCategoryDict: this.getDictLabel( "equipment_category", item.equipmentCategory ), equipmentSubcategoryDict: this.getDictLabel( "equipment_subcategory", item.equipmentSubcategory ), ownershipTypeDict: this.getDictLabel( "ownership_type", item.ownershipType ), equipmentStatusDict: this.getDictLabel( "equipment_status", item.equipmentStatus ), storageStatusDict: this.getDictLabel( "storage_status", item.storageStatus ), inspectionStatusDict: this.getDictLabel( "inspection_status", item.inspectionStatus ), }; }); }, // 新增方法:根据字典和代码获取标签 getDictLabel(dictType, value) { const dict = this[dictType] || []; const item = dict.find((d) => d.entrycode === value); return item ? item.entryname : value; }, // 每页数 sizeChangeHandle(val) { this.pageSize = val; this.pageIndex = 1; this.getDataList(); }, // 当前页 currentChangeHandle(val) { this.pageIndex = val; this.getDataList(); }, //重置表格 resetForm(formName) { this.$refs[formName].resetFields(); this.purchaseDateList = []; this.lastVerificationDateList = []; this.getDataList(); }, // 新增 / 修改 addOrUpdateHandle(data) { this.addOrUpdateVisible = true; this.$nextTick(() => { this.$refs.addOrUpdate.init(data); }); }, // 删除 deleteHandle(id) { if (this.dataListSelections.length === 0 && !id) { this.$message({ message: "请选择数据", type: "warning", }); return; } var ids = id ? [id] : this.dataListSelections.map((item) => { return item.id; }); this.$confirm( `确定进行[${ids.length == 1 ? "删除" : "批量删除"}]操作?`, "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", } ).then(() => { delCmmsEquipmentInfo(ids).then(({ data }) => { if (data.code === 0) { this.getDataList(); this.$message.success("删除成功"); } else { this.$message.error(data.msg); } }); }); }, }, }; </script> 2.详情页面代码 <template> <dialog-edit :visible.sync="open" :title="activeTitle" @close="handleDialogClose" @changeTab="handleTabChange" dialogType="dialog_detail" :menuTab="pageMenuTab" :reserve="true" width="900px" height="650px" > <!-- 设备台账详情页 --> <template v-slot:equipmentDetail> <div class="dialog-content-wrap"> <formlist v-if="dictLoaded" :form="form" :form2="formData" :dictData="dictData" ref="formList" :readonly="true" :width="'120px'" /> </div> </template> <!-- 气量检测页 --> <template v-slot:GasMeasurement> <div class="dialog-content-wrap" v-if="GasMeasurementReady"> <gas-detection ref="GasMeasurementRef" :equipment-id="currentEquipmentId" @on-new="handleNewDetection" @on-delete="handleDeleteDetection" /> </div> </template> <template v-slot:footer> <div class="dialog_footer"> <el-button @click="handleCancel">关闭</el-button> </div> </template> </dialog-edit> </template> <script> import { getDictionaries } from "@/utils"; import GasMeasurement from "../cmmsGasMeasurement/cmmsGasMeasurement.vue"; // 需要导入API函数 import { getCmmsEquipmentInfo } from "@/api/cmmsEquipmentInfo/cmmsEquipmentInfo.js"; export default { name: "EquipmentDetailDialog", components: { GasMeasurement, }, data() { return { dictLoaded: false, form: [ { arr: [ { code: "equipmentCode", title: "设备编码", type: 0, readonly: true, verification: true, rule: "0", customTips: "", regular: "", dictionary: "", }, { code: "equipmentCategory", title: "设备大类", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择设备大类", dictionary: "equipment_category", }, { code: "equipmentSubcategory", title: "设备小类", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择设备小类", dictionary: "equipment_subcategory", }, { code: "modelDescription", title: "燃气表型号描述", type: 0, readonly: true, verification: true, rule: "0", customTips: "燃气表的具体型号描述", regular: "", }, { code: "specificationModel", title: "规格型号", type: 0, readonly: true, verification: true, rule: "0", customTips: "设备的规格型号", regular: "", }, { code: "accuracyLevel", title: "器具准确度等级", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择准确度等级", dictionary: "accuracy_level", }, { code: "manufacturer", title: "器具生产单位", type: 0, readonly: true, verification: true, rule: "0", customTips: "设备的生产厂家", regular: "", }, { code: "ownershipType", title: "归属类型", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择设备归属类型", dictionary: "ownership_type", }, { code: "equipmentOwner", title: "设备归属方", type: 0, readonly: true, verification: true, rule: "0", customTips: "设备的所有者", regular: "", }, { code: "purchaseDate", title: "采购日期", type: 6, readonly: true, verification: true, rule: "0", customTips: "请选择采购日期", dateType: "date", dateFormat: "yyyy-MM-dd", }, { code: "storageLocation", title: "存放位置", type: 0, readonly: true, verification: true, rule: "0", customTips: "设备当前的存放位置", regular: "", }, { code: "overdueYears", title: "超期年限(年)", type: 3, readonly: true, verification: true, rule: "0", customTips: "超出检定有效期的年限", regular: "^[0-9]{1,2}$", min: 0, max: 20, }, { code: "lastVerificationDate", title: "最后检定日期", type: 6, readonly: true, verification: true, rule: "0", customTips: "请选择最后检定日期", dateType: "date", dateFormat: "yyyy-MM-dd", }, { code: "equipmentStatus", title: "设备状态", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择设备当前状态", dictionary: "equipment_status", }, { code: "storageStatus", title: "仓储状态", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择仓储状态", dictionary: "storage_status", }, { code: "inspectionStatus", title: "检测状态", type: 1, readonly: true, verification: true, rule: "0", customTips: "请选择检测状态", dictionary: "inspection_status", }, { code: "equipmentPhoto", title: "设备照片", type: 30, readonly: true, verification: true, rule: "0", customTips: "请上传设备照片", multiple: false, fileNum: 1, accept: "image/jpeg,image/png", maxSize: 5, }, { code: "remarks", title: "备注", type: 2, readonly: true, verification: true, rule: "0", customTips: "请填写备注信息", rows: 4, }, ], }, ], formData: {}, open: false, dictData: {}, active: "equipmentDetail", activeTitle: "设备详情", currentEquipmentId: null, GasMeasurementReady: false, pageMenuTab: [ { title: "基础信息", sxTitle: "equipmentDetail", hide: false, icon: "el-icon-document", }, { title: "气量监测", sxTitle: "GasMeasurement", hide: false, icon: "el-icon-data-line", }, ], }; }, methods: { async init(row) { this.open = true; this.active = "equipmentDetail"; this.activeTitle = "基础详情"; this.currentEquipmentId = row.id; this.dictLoaded = false; this.GasMeasurementReady = false; this.formData = {}; try { // 兼容性写法替代 Promise.allSettled const dictPromise = this.loadDictData().then( value => ({ status: 'fulfilled', value }), reason => ({ status: 'rejected', reason }) ); const detailPromise = this.loadEquipmentDetail(row.id).then( value => ({ status: 'fulfilled', value }), reason => ({ status: 'rejected', reason }) ); const [dictResult, detailResult] = await Promise.all([dictPromise, detailPromise]); // 处理字典加载结果 if (dictResult.status === 'rejected') { console.error("字典加载失败:", dictResult.reason); } // 处理设备详情加载结果 if (detailResult.status === 'rejected') { console.error("设备详情加载失败:", detailResult.reason); this.useRowDataAsFallback(row); // 使用回退数据 } else if (detailResult.status === 'fulfilled') { this.formData = detailResult.value; } this.dictLoaded = true; } catch (error) { console.error("初始化异常:", error); this.useRowDataAsFallback(row); // 使用回退数据 this.dictLoaded = true; } }, async loadEquipmentDetail(equipmentId) { try { const response = await getCmmsEquipmentInfo(equipmentId); // 增加响应为 undefined 的检查 if (!response) { throw new Error("API返回空响应"); } // 检查响应结构,避免访问 undefined.data if (response.data.code === 0 && response.data.data) { const detailData = response.data.data; return { ...detailData, purchaseDate: detailData.purchaseDate ? this.formatDate(detailData.purchaseDate) : null, lastVerificationDate: detailData.lastVerificationDate ? this.formatDate(detailData.lastVerificationDate) : null }; } else { throw new Error(response.data.msg || "设备详情数据格式错误"); } } catch (error) { throw new Error(`加载设备详情失败: ${error.message}`); } }, async loadDictData() { const dictKeys = [ "equipment_category", "equipment_subcategory", "accuracy_level", "ownership_type", "equipment_status", "storage_status", "inspection_status", ]; try { const data = await getDictionaries(dictKeys); this.dictData = Object.fromEntries( dictKeys.map((key) => [key, data[key] || []]) ); } catch (error) { console.error("加载字典数据失败:", error); this.dictData = Object.fromEntries(dictKeys.map((key) => [key, []])); } }, formatDate(dateString) { return dateString ? new Date(dateString).toISOString().split("T")[0] : null; }, // 添加这个方法 handleDialogClose() { this.handleCancel(); this.$emit("close"); // 确保触发close事件 }, handleCancel() { this.open = false; this.GasMeasurementReady = false; this.$emit("closed"); }, handleTabChange(activeTab) { this.active = activeTab; const activeItem = this.pageMenuTab.find(item => item.sxTitle === activeTab); if (activeItem) { this.activeTitle = activeItem.title; } if (activeTab === "GasMeasurement") { // 确保设备ID已设置后再渲染组件 this.GasMeasurementReady = !!this.currentEquipmentId; this.$nextTick(() => { if (this.$refs.GasMeasurementRef) { this.$refs.GasMeasurementRef.refreshData(); } }); } }, }, mounted() { // 确保组件正常挂载 this.$nextTick(() => { console.log("formList组件实例:", this.$refs.formList); }); } }; </script> <style scoped> .dialog-content-wrap { padding: 15px; height: 100%; overflow: auto; } </style> 我的js文件 import request from '@/utils/httpRequest'; // 查询设备管理-设备台账列表 export function listCmmsEquipmentInfo(query) { return request({ url: request.adornUrl('/cmmsEquipmentInfo/cmmsEquipmentInfo/page-list'), method: 'get', params: query }) } // 查询设备管理-设备台账详细 export function getCmmsEquipmentInfo(id) { return request({ url: request.adornUrl('/cmmsEquipmentInfo/cmmsEquipmentInfo/info/' + id), method: 'get' }) } // 新增设备管理-设备台账 export function addCmmsEquipmentInfo(data) { return request({ url: request.adornUrl('/cmmsEquipmentInfo/cmmsEquipmentInfo/add'), method: 'post', data: data }) } // 修改设备管理-设备台账 export function updateCmmsEquipmentInfo(data) { return request({ url: request.adornUrl('/cmmsEquipmentInfo/cmmsEquipmentInfo/update'), method: 'post', data: data }) } // 删除设备管理-设备台账 export function delCmmsEquipmentInfo(data) { return request({ url: request.adornUrl('/cmmsEquipmentInfo/cmmsEquipmentInfo/delete'), method: 'post', data: data }) } 问题是,详情的页面怎么展示不出来
最新发布
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是言若呀~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值