$route.params是否可以手动删除?

在Vue框架中,删除$route.params属性的方法取决于Vue的版本和路由模式。在Vue2.x的hash模式下,可以使用delete关键字,但在Vue3.x或history模式中,$route对象是只读的,应使用Object.assign()创建新对象并删除参数,再通过$router.push()更新路由。

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

通过与chatGpt不断的反问交流,终于获得了最终答案,回答如下,

chatGpt:
非常抱歉,我的回答还有误,非常感谢您的指正。
经过进一步的研究和测试,我发现在某些情况下,确实可以使用 delete 关键字删除$route.params 对象的属性,例如在 Vue 2.x 版本中,如果使用的是 hash 模式,那么 $route.params 对象中的属性是响应式的,此时可以使用 delete 关键字删除属性
但是在其他情况下,比如在 Vue 3.x 版本中或者使用 history 模式时,$route.params 对象中的属性不是响应式的,并且 $route 对象本身是只读的,无法通过 delete 关键字删除其属性。
因此,对于 $route.params 对象中的属性删除操作,我们应该尽量避免使用 delete 关键字,而是使用 Object.assign() 方法创建一个新对象,并删除对应参数,然后通过 $router.push() 方法进行路由跳转实现参数变更。
再次感谢您的指正,希望我的回答能够更加准确地回答您的问题。

与chatGpt的交流过程

1.

chatGpt在第一次回答的答案
在第一次回答后,我通过delete this.$route.params 测试是否手动删除成功,最后尝试可以手动删除成功 (上方图片我写错了,应该为$route,不是$router)

2.

chatGpt在第二次回答的答案

3.

chatGpt在第三次回答的答案
最后还是得说,chatGpt牛逼!

<template> <div> <header class="ant-layout-header header_sd-header_common"> <div class="left_sd-header_common"> <div class="logo_sd-webflow_webflow"> <h3>激励考核指下发</h3> </div> </div> <div class="right_sd-header_common"> <a-button v-if="!readonly" type="link" icon="save" class="button_sd-webflow-button_webflow" @click="save" > 保存 </a-button> <a-button v-if="!readonly" type="link" icon="save" class="button_sd-webflow-button_webflow" @click="xfClick" > 下发 </a-button> <a-button type="link" icon="close-circle" class="button_sd-webflow-button_webflow" @click="btnClose" > 退出 </a-button> </div> </header> <div class="budget-record"> <div class="budget-record-table"> <h2 class="budget-record-table-title">激励考核指下发</h2> <a-form-model ref="ruleForm" :rules="rules" :model="project" class="sitd-apply" layout="horizontal" > <table> <colgroup> <col width="170px" /> <col /> <col width="170px" /> <col /> </colgroup> <tr> <td class="ant-form-item-label cell_sd-form-item-td-label_common"> <label title="指标编号">指标编号</label> </td> <td class="ant-form-item-control-wrapper" :colspan="3"> <a-form-model-item prop="zbbh"> <template>{{ project['zbbh'] }}</template> </a-form-model-item> </td> </tr> <tr> <td class="ant-form-item-label cell_sd-form-item-td-label_common"> <label title="指标年度" class="ant-form-item-required">指标年度</label> </td> <td class="ant-form-item-control-wrapper"> <a-form-model-item prop="zbnd"> <!-- 修改为下拉选择框 --> <a-select v-if="!readonly" v-model="project['zbnd']" placeholder="请选择年份" style="width: 100%" > <!-- 生成年份选项 --> <a-select-option v-for="year in yearOptions" :key="year" :value="year"> {{ year }} </a-select-option> </a-select> <template v-else> {{ project['zbnd'] }} </template> </a-form-model-item> </td> <td class="ant-form-item-label cell_sd-form-item-td-label_common"> <label title="考核周期">考核周期</label> </td> <td class="ant-form-item-control-wrapper"> <a-form-model-item prop="khzq"> <a-input v-if="!readonly" v-model="project['khzq']" placeholder="考核周期" /> <template v-else>{{ project['khzq'] }}</template> </a-form-model-item> </td> </tr> <tr> <td class="ant-form-item-label cell_sd-form-item-td-label_common"> <label title="考核对象">考核对象</label> </td> <td class="ant-form-item-control-wrapper"> <a-form-model-item prop="khdx"> <a-select v-if="!readonly" v-model="selectedKhdxIds" mode="multiple" style="width: 100%" placeholder="请选择被考核对象" @change="handleKhdxChange" > <template v-for="(item, _i) in khdxList"> <a-select-option :key="item.code" :value="item.code">{{ item.value }}</a-select-option> </template> </a-select> <template v-else>{{ project['khdx'] }}</template> </a-form-model-item> </td> <td class="ant-form-item-label cell_sd-form-item-td-label_common"> <label title="创建日期" class="ant-form-item-required">创建日期</label> </td> <td class="ant-form-item-control-wrapper"> <a-form-model-item prop="cjrq"> <template>{{ project['cjrq'] ? refreshTime(project['cjrq']) : '' }}</template> </a-form-model-item> </td> </tr> <tr> <td class="ant-form-item-label cell_sd-form-item-td-label_common upload-td"> <label title="说明">说明</label> </td> <td class="ant-form-item-control-wrapper" colspan="3"> <a-form-model-item prop="sm"> <div v-if="!readonly" class="textarea-wrapper"> <a-textarea v-model="project['sm']" placeholder="请输入内容" :max-length="300" class="m-textarea" :auto-size="{ minRows: 3, maxRows: 5 }" /> <span class="m-count">{{ `${project['sm']?.length || 0}/300` }}</span> </div> <template v-else>{{ project['sm'] }}</template> </a-form-model-item> </td> </tr> </table> </a-form-model> <!-- 这里暂时去掉,根据客户描述,一年只进行一次年度考核和激励考核,因此根据年度和单位关联即可 --> <!-- <h3 class="budget-record-table-title">关联年度考核</h3> <a-button v-if="!readonly" type="primary" :style="{ marginLeft: '88px' }" class="button_sd-webflow-button_webflow" @click="openDialogGl" > 关联年度考核 </a-button> <a-button v-if="!readonly" :style="{ marginLeft: '8px' }" class="button_sd-webflow-button_webflow" :disabled="!ndkhSelectedRowKeys.length" @click="ndkhBeforDelete" > 删除 </a-button> <a-modal title="选择年度考核" :visible="dialogVisibleGl" width="80%" @ok="handleDialogConfirm" @cancel="dialogVisibleGl = false" > <div class="apply-search"> <a-form-model :form="searchForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }"> <a-row :gutter="24"> <a-col :span="8" class="chd"> <a-form-model-item label="考核年度"> <a-input v-model="searchForm['khnd']" allow-clear placeholder="请输入指标年度" /> </a-form-model-item> </a-col> <a-col :span="8" class="chd"> <a-form-model-item label="考核周期"> <a-input v-model="searchForm['khzq']" allow-clear placeholder="请输入考核周期" /> </a-form-model-item> </a-col> </a-row> <a-row> <a-col :span="24" class="chd" :style="{ textAlign: 'right', lineHeight: '45px' }"> <a-button :style="{ marginRight: '8px' }" @click="reset"> 重置 </a-button> <a-button type="primary" html-type="submit" @click="btnSearchBusinessList"> 查询 </a-button> </a-col> </a-row> </a-form-model> </div> <a-divider style="margin: 12px 0" /> <SdTable ref="ndkh" row-key="id" :columns="ndkhColumns" :data-source.sync="dialogResult" :pagination="paginationOpt" :loading="dialogLoading" :scroll="{ x: 1500 }" :row-selection="{ selectedRowKeys: selectedRowKeysAdd, onChange: btnSelectProjectAdd, }" > </SdTable> </a-modal> <SdTable ref="ndkhTable" row-key="id" :columns="ndkhColumns" :data-source.sync="ndkhResult" :loading="ndkhLoading" :pagination="false" class="ant-table" :row-selection="{ selectedRowKeys: ndkhSelectedRowKeys, onChange: btnSelectProjectNdkh, }" > </SdTable> --> <h3 class="budget-record-table-title" style="margin-top: 18px">激励考核指标</h3> <a-button v-if="!readonly" type="primary" :style="{ marginLeft: '88px' }" class="button_sd-webflow-button_webflow" @click="openDialog" > 新增 </a-button> <a-button v-if="!readonly" :style="{ marginLeft: '8px' }" class="button_sd-webflow-button_webflow" :disabled="!selectedRowKeys.length" @click="btnBeforDelete" > 删除 </a-button> <SdTable ref="jlkhzbxf" row-key="id" :columns="jlkhzbxfColumns" :data-source.sync="jlkhzbxfResult" :loading="loading" :pagination="false" class="ant-table" bordered :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: btnSelectProject, }" > <!-- 指标内容列自定义渲染 --> <template slot="指标内容" slot-scope="text, record, index"> <div style="white-space: pre-line; text-align: left; padding: 8px 0"> {{ text }} </div> </template> <template slot="分值" slot-scope="text, record, index"> <div style="white-space: pre-line; text-align: left; padding: 8px 0"> {{ text }} </div> </template> <!-- 操作列 --> <template v-if="!readonly" slot="操作" slot-scope="text, record"> <a-button class="action-button" type="link" size="small" @click="btnOpenProjectDetails(record)" > 编辑 </a-button> </template> </SdTable> <a-modal title="激励考核指标" :visible="dialogVisible" width="35%" @ok="handleConfirm" @cancel="handleCancel" > <div class="apply-search"> <a-form-model ref="subFormRef" :rules="jlkhzbxfSubRules" :form="jlkhzbxfSubForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" > <a-row> <a-col :span="18"> <a-form-model-item label="指标类别"> <a-input v-model="jlkhzbxfSubForm['zblb']" allow-clear placeholder="请输入指标类别" /> </a-form-model-item> </a-col> </a-row> <a-row> <a-col :span="18"> <a-form-model-item label="指标内容"> <a-textarea v-model="jlkhzbxfSubForm['zbnr']" placeholder="请输入指标内容(按Enter换行)" :max-length="300" class="m-textarea" :auto-size="{ minRows: 3, maxRows: 6 }" /> </a-form-model-item> </a-col> </a-row> <a-row> <a-col :span="18"> <a-form-model-item label="分值"> <a-textarea v-model="jlkhzbxfSubForm['fz']" placeholder="请输入分值(按Enter换行)" :max-length="300" class="m-textarea" :auto-size="{ minRows: 2, maxRows: 4 }" /> </a-form-model-item> </a-col> </a-row> <a-row> <a-col :span="18"> <a-form-model-item label="分值上限"> <a-input v-model="jlkhzbxfSubForm['fzsx']" allow-clear placeholder='例如:"+1分"、"-1.5分"或"不设上限"' /> </a-form-model-item> </a-col> </a-row> </a-form-model> </div> </a-modal> </div> </div> </div> </template> <script> import { Message, Modal } from 'ant-design-vue' import moment from 'moment' import components from './_import-components/zk-jlkh-zbxf-import' import KhypjService from './khypj-service' import crossWindowWatcher from '@/common/services/cross-window-watcher' import SdTable from '@/common/components/sd-table.vue' export default { name: 'ZkJlkhZbxf', metaInfo: { title: '激励考核指标下发', }, components: { ...components, SdTable, }, props: { id: { type: String, default: undefined, }, }, data() { // 添加校验规则 const validateFzsx = (rule, value, callback) => { if (!value) { callback() return } // 允许"不设上限" if (value === '不设上限') { callback() return } // 验证格式: ±数字(可含小数) + 单位(非数字字符) const regex = /^[+-]\d+(\.\d+)?[^\d]+$/ if (!regex.test(value)) { callback(new Error('格式错误,请填写"不设上限"或类似"+1分"、"-1.5分"的格式')) } else { callback() } } return { loading: false, ndkhLoading: false, dialogLoading: false, readonly: true, yearOptions: this.generateYearOptions(), rules: { zbnd: [{ required: true, message: '请选择指标年度', trigger: 'blur' }], }, jlkhzbxfSubRules: { fzsx: [{ validator: validateFzsx, trigger: 'blur' }], }, // 新增搜索表单数据 searchForm: { khnd: undefined, // 考核年度 khzq: undefined, // 考核周期 }, project: { id: undefined, // 主键id zbbh: undefined, // 指标编号 cjrq: undefined, // 创建日期 zbnd: undefined, // 指标年度 khzq: undefined, // 考核周期 khdx: undefined, // 考核对象 khdxId: undefined, // 考核对象id sm: undefined, // 说明 status: undefined, // 指标状态:0暂存,1下发(不可修改) ndkhId: undefined, // 关联的年度考核id }, jlkhzbxfResult: [], jlkhzbxfSubForm: { id: undefined, // id mainId: undefined, // 主表id zblb: undefined, // 指标类别 zbnr: undefined, // 指标内容 fz: undefined, // 分值 fzsx: undefined, // 分值上限 }, ndkhResult: [], khdxList: [], selectedKhdxIds: [], // 用于多选绑定的临时ID数组 dialogVisible: false, dialogVisibleGl: false, selectedKeys: [], selectedRows: [], selectedRowKeys: [], ndkhSelectedRowKeys: [], // 年度考核表格的选中项 ndkhSelectedRows: [], // 年度考核表格选中的行数据 selectedKeysAdd: [], selectedRowKeysAdd: [], // 年度考核表格的选中项 selectedRowsAdd: [], // 年度考核表格选中的行数据 isUpdateJlkhzbxfSub: false, isXf: false, ndkhColumns: [ { title: '考核编号', dataIndex: 'khbh', scopedSlots: { customRender: '考核编号', }, width: '200px', align: 'center', }, { title: '考核年度', dataIndex: 'khnd', scopedSlots: { customRender: '指标年度', }, width: '70px', align: 'center', }, { title: '考核对象', dataIndex: 'khdx', scopedSlots: { customRender: '责任主体', }, width: '200px', align: 'center', }, { title: '考核周期', dataIndex: 'khzq', scopedSlots: { customRender: '考核周期', }, width: '100px', align: 'center', }, ], dialogResult: [], dialogColumns: [], paginationOpt: { current: 1, // 当前页码 pageSize: 10, // 当前每页大小 total: 0, // 总数 showSizeChanger: true, showQuickJumper: false, pageSizeOptions: ['10', '20', '40', '60', '80', '100'], showTotal: (total) => `共 ${total} 条`, onShowSizeChange: (current, pageSize) => { this.paginationOpt.current = 1 this.paginationOpt.pageSize = pageSize this.btnSearchBusinessList() }, onChange: (current, size) => { this.paginationOpt.current = current this.paginationOpt.pageSize = size this.btnSearchBusinessList() }, }, } }, computed: { // 动态计算列配置 jlkhzbxfColumns() { const baseColumns = [ { title: '序号', customRender: (text, record, index) => { return index + 1 }, align: 'center', width: '10%', }, { title: '指标类别', dataIndex: 'zblb', customRender: (text, record) => { // 只有显示行才渲染内容 if (record.rowSpan > 0) { return { children: text, attrs: { rowSpan: record.rowSpan }, } } return { attrs: { rowSpan: 0 } } }, align: 'center', width: '10%', }, { title: '指标内容', dataIndex: 'zbnr', scopedSlots: { customRender: '指标内容', }, align: 'center', width: '40%', }, { title: '分值', dataIndex: 'fz', scopedSlots: { customRender: '分值', }, align: 'center', width: '20%', }, { title: '分值上限', dataIndex: 'fzsx', scopedSlots: { customRender: '分值上限', }, align: 'center', width: '10%', }, ] // 非只读模式下添加操作列 if (!this.readonly) { baseColumns.push({ title: '操作', dataIndex: 'action', scopedSlots: { customRender: '操作' }, width: '10%', align: 'center', }) } return baseColumns }, }, watch: { jlkhzbxfResult: { handler(newVal) { this.calculateRowSpans(newVal) }, immediate: true, // 初始化时立即执行 deep: true, // 深度监听 }, }, created() { this.getKhdxList() this.jlkhzbxfResult = this.calculateRowSpans(this.jlkhzbxfResult) this.initJlkhzbxfInfo() }, mounted() { if (!this.$route.query.id) { this.project.zbbh = this.getZBbh() this.project.cjrq = moment(new Date()).format('YYYY-MM-DD') this.readonly = false } }, methods: { // 年度考核表格选中处理 btnSelectProjectNdkh(selectedRowKeys, selectedRows) { this.ndkhSelectedRowKeys = selectedRowKeys this.ndkhSelectedRows = [...selectedRows] }, btnSelectProjectAdd(selectedRowKeys, selectedRows) { this.selectedRowKeysAdd = selectedRowKeys this.selectedRowsAdd = [...selectedRows] }, // 重置搜索表单 reset() { this.searchForm = { khnd: undefined, // 考核年度 khzq: undefined, // 考核周期 } this.paginationOpt.current = 1 this.paginationOpt.pageSize = 10 this.btnSearchBusinessList() }, getKhzbxfInfo() { console.log('1111111----------', this.project) console.log('22222222----------', this.project.ndkhId) if (this.project.ndkhId) { KhypjService.getKhzbxfById(this.project.ndkhId).then((res) => { if (res.data.code === 200) { if (res.data.data) { this.ndkhResult.push(res.data.data) } else { this.ndkhResult = [] } } else { Message.error('获取考核指标下发信息失败!') } }) } }, ndkhBeforDelete() { const _this = this if (_this.ndkhSelectedRowKeys.length === 0) { Message.warning('请选择要删除的数据!') return } Modal.confirm({ content: '是否确认删除?', onOk() { _this.project.ndkhId = '-1' _this.saveJlkhzbxf() _this.ndkhResult = [] _this.ndkhSelectedRowKeys = [] // 清空选中状态 }, onCancel() {}, }) }, openDialogGl() { console.log('3333----------', this.ndkhResult) if (this.ndkhResult.length > 0) { Message.warning('只能关联一条年度考核!') return } this.dialogVisibleGl = true this.selectedKeysAdd = [] this.selectedRowsAdd = [] this.btnSearchBusinessList() }, handleDialogConfirm() { if (this.selectedRowsAdd.length === 0) { Message.warning('请选择一条年度考核!') return } if (this.selectedRowsAdd.length > 1) { Message.warning('只能关联一条年度考核!') return } this.project.ndkhId = this.selectedRowsAdd[0].id this.saveJlkhzbxf() this.getKhzbxfInfo() this.dialogVisibleGl = false }, btnSearchBusinessList() { this.dialogLoading = true const khzbxfSearchVo = { khnd: this.searchForm.khnd, khzq: this.searchForm.khzq, } const params = { current: this.paginationOpt.current, // 直接使用当前页码 pageSize: this.paginationOpt.pageSize, // 直接使用当前每页大小 searchVo: khzbxfSearchVo, } KhypjService.getNdkhList(params) .then((res) => { if (res.data.code === 200) { this.paginationOpt.total = res.data.data.total this.dialogResult = res.data.data.records } else { Message.error('查询失败!') } }) .catch((err) => { Message.error(err.message || err.data) this.paginationOpt.total = 0 this.dialogResult = [] }) .finally(() => { this.dialogLoading = false }) }, getKhdxList() { KhypjService.getCodeList('khdx').then((res) => { if (res.data.code === 200) { this.khdxList = res.data.data } else { Message.error('查询失败!') } }) }, // 处理考核对象选择变化 handleKhdxChange(selectedIds) { // 1. 拼接ID字符串 this.project.khdxId = selectedIds.join(';') // 2. 拼接名称字符串 const selectedNames = [] selectedIds.forEach((code) => { const item = this.khdxList.find((d) => d.code === code) if (item) { selectedNames.push(item.value) } }) this.project.khdx = selectedNames.join(';') }, btnBeforDelete() { const _this = this if (this.selectedRowKeys.length === 0) { Message.warning('请选择要删除的数据!') return } Modal.confirm({ content: '是否确认删除?', onOk() { _this.deleteJlkhzbxfSub() _this.selectedRowKeys = [] }, onCancel() {}, }) }, deleteJlkhzbxfSub() { KhypjService.removeJlkhzbxfSubByIds(this.selectedRowKeys).then((res) => { if (res.data.code === 200) { Message.success('删除成功!') this.getJlkhzbxfSubList() } else { Message.error('查询失败!') } }) }, btnSelectProject(selectedRowKeys, selectedRows) { this.selectedRowKeys = selectedRowKeys this.selectedRows = [...selectedRows] }, openDialog() { this.dialogVisible = true this.selectedKeys = [] this.selectedRows = [] this.jlkhzbxfSubForm = { id: undefined, // id mainId: this.$route.query.id, // 主表id zblb: undefined, // 指标类别 zbnr: undefined, // 指标内容 fz: undefined, // 分值 fzsx: undefined, // 分值上限 } // 新增子数据自动保存主数据 if (!this.$route.query.id) { this.saveJlkhzbxf() } }, btnOpenProjectDetails(record) { this.dialogVisible = true this.jlkhzbxfSubForm = { id: record.id, // id mainId: record.mainId, // 主表id zblb: record.zblb, // 指标类别 zbnr: record.zbnr, // 指标内容 fz: record.fz, // 分值 fzsx: record.fzsx, // 分值上限 } this.isUpdateJlkhzbxfSub = true console.log('121212------', record) console.log('33333222------', this.jlkhzbSubxfForm) }, handleCancel() { this.dialogVisible = false }, // 弹窗确认 handleConfirm() { // 添加表单校验 this.$refs.subFormRef.validate((valid) => { if (!valid) { return false } // 原有的保存逻辑... if (!this.isUpdateJlkhzbxfSub) { this.jlkhzbxfSubForm.mainId = this.$route.query.id // 保存子表数据 KhypjService.saveJlkhzbxfSub(this.jlkhzbxfSubForm).then((res) => { if (res.data.code === 200) { Message.success(`添加成功!`) this.getJlkhzbxfSubList() } else { Message.error('添加失败!') } }) } else { // 保存子表数据 KhypjService.updateJlkhzbxfSub(this.jlkhzbxfSubForm).then((res) => { if (res.data.code === 200) { Message.success(`修改成功!`) this.getJlkhzbxfSubList() } else { Message.error('修改失败!') } }) this.isUpdateJlkhzbxfSub = false } this.dialogVisible = false }) }, // handleConfirm() { // if (!this.isUpdateJlkhzbxfSub) { // this.jlkhzbxfSubForm.mainId = this.$route.query.id // // 保存子表数据 // KhypjService.saveJlkhzbxfSub(this.jlkhzbxfSubForm).then((res) => { // if (res.data.code === 200) { // Message.success(`添加成功!`) // this.getJlkhzbxfSubList() // } else { // Message.error('添加失败!') // } // }) // } else { // // 保存子表数据 // KhypjService.updateJlkhzbxfSub(this.jlkhzbxfSubForm).then((res) => { // if (res.data.code === 200) { // Message.success(`修改成功!`) // this.getJlkhzbxfSubList() // } else { // Message.error('修改失败!') // } // }) // this.isUpdateJlkhzbxfSub = false // } // this.dialogVisible = false // }, // 计算行合并 calculateRowSpans(data) { if (!data || data.length === 0) return data const categoryMap = {} // 第一步:统计每个类别的行数 data.forEach((item) => { categoryMap[item.zblb] = (categoryMap[item.zblb] || 0) + 1 }) // 第二步:设置行合并属性 let lastCategory = null return data.map((item) => { // 重置rowSpan属性 item.rowSpan = undefined if (item.zblb !== lastCategory) { lastCategory = item.zblb // 只有每个类别的第一行设置rowSpan item.rowSpan = categoryMap[item.zblb] return item } // 同类别的后续行设置rowSpan为0 item.rowSpan = 0 return item }) }, // 生成年份选项 generateYearOptions() { const currentYear = new Date().getFullYear() const years = [] // 添加年份:当前年后1年、本年、前1年、前2年 years.push(currentYear + 1) // 后1年 years.push(currentYear) // 本年 years.push(currentYear - 1) // 前1年 years.push(currentYear - 2) // 前2年 return years }, btnClose() { window.close() }, initJlkhzbxfInfo() { if (this.$route.query.id) { KhypjService.getJlkhzbxfById(this.$route.query.id).then((res) => { if (res.data.code === 200) { this.project = res.data.data this.project.cjrq = this.project.cjrq ? moment(new Date(this.project.cjrq)).format('YYYY-MM-DD') : null this.readonly = this.project.status === 1 // 初始化选中项 if (this.project.khdxId) { this.selectedKhdxIds = this.project.khdxId.split(';').filter(Boolean) } this.getJlkhzbxfSubList() this.getKhzbxfInfo() } else { Message.error('获取考核指标库信息失败!') } }) } }, save() { const _this = this this.$refs.ruleForm.validate((valid, obj) => { if (!valid) { Message.warning('请输入必填项!') return false } else { _this.saveJlkhzbxf() } }) }, xfClick() { this.readonly = true this.isXf = true this.save() KhypjService.jlkhzbzpXfStart(this.$route.query.id).then((res) => { if (res.data.code === 200) { Message.success('下发成功!') } else { Message.error('下发失败!') } }) }, // 修改 saveJlkhzbxf 方法返回 Promise saveJlkhzbxf() { const _this = this if (this.isXf) { this.project.status = 1 } else { this.project.status = 0 } // 创建数据副本,避免污染原始数据 const postData = { ...this.project } // 仅在值是字符串时才进行转换 if (postData.cjrq && typeof postData.cjrq === 'string') { postData.cjrq = this.strToTimestamp(postData.cjrq) } // 返回一个 Promise return new Promise((resolve, reject) => { // 判断是新增还是更新 const apiCall = !this.$route.query.id ? KhypjService.saveJlkhzbxf(postData) : KhypjService.updateJlkhzbxf(postData) apiCall .then((res) => { if (res.data.code === 200) { // 处理新增保存成功 if (!_this.$route.query.id) { Message.success('保存成功!') if (res.data.data) { const currentUrl = window.location.href const newUrl = currentUrl.replace('zbxf', `zbxf?id=${res.data.data}`) // 直接跳转页面,不需要等待初始化 window.location.href = newUrl } resolve() // 解析 Promise } // 处理更新保存成功 else { if (_this.project.status === 1) { Message.success('提交成功!') } else { Message.success('保存成功!') } resolve() // 解析 Promise } } else { // 处理失败情况 const errorMessage = !_this.project.id ? '保存失败!' : _this.project.status === 1 ? '提交失败!' : '保存失败!' Message.error(errorMessage) reject(new Error(res.data.message || errorMessage)) } }) .catch((error) => { // 处理 API 错误 const errorMessage = !_this.project.id ? '保存失败!' : _this.project.status === 1 ? '提交失败!' : '保存失败!' console.error('API 错误:', error) Message.error(errorMessage) reject(error) }) }) }, getJlkhzbxfSubList() { KhypjService.getJlkhzbxfSubList(this.$route.query.id).then((res) => { if (res.data.code === 200) { this.jlkhzbxfResult = res.data.data } else { Message.error('获取子表信息失败!') } }) }, // 获取唯一指标编号 getZBbh() { // 获取当前时间 const now = new Date() // 获取当前时间的年、月、日、时、分、秒、毫秒 const year = now.getFullYear() const month = String(now.getMonth() + 1).padStart(2, '0') const day = String(now.getDate()).padStart(2, '0') const hour = String(now.getHours()).padStart(2, '0') const minute = String(now.getMinutes()).padStart(2, '0') const second = String(now.getSeconds()).padStart(2, '0') const millisecond = String(now.getMilliseconds()).padStart(3, '0') // 生成唯一标识 const uniqueId = `${year}${month}${day}${hour}${minute}${second}${millisecond}` return 'JLKHZBXF-' + uniqueId }, strToTimestamp(dateStr) { const date = moment(dateStr, 'YYYY-MM-DD') return date.valueOf() }, refreshTime(item) { return moment(item).format('YYYY-MM-DD') }, }, } </script> <style lang="scss" scoped> /* 设置表格宽度 */ .ant-table { width: 90%; margin: auto; /* 居中显示 */ } .sitd-collapse-block { width: 90%; margin: auto; &::v-deep(.ant-collapse-content-box) { padding: unset !important; } } table { width: 90%; margin: auto; border-top: 1px solid #e8e8e8; margin-bottom: 16px; table-layout: fixed; tr td { border-left: 1px solid #e8e8e8; border-bottom: 1px solid #e8e8e8; min-height: 100px; &:first-child { border-left: unset; } &:nth-child(2n + 1) { background: #fafafa; width: 170px; } &.upload-td { background: #fafafa; width: 170px !important; } &.upload-time-td { background: #fafafa; width: 200px !important; } &.ant-form-item-check { width: 194px !important; } .ant-form-item { margin-bottom: unset !important; padding: 5px; .ant-form-item-label { width: 170px; padding-bottom: 1px; text-align: center; background-color: #fafafa; } } &::v-deep(label) { display: block; margin: 0 auto; text-align: right; white-space: normal; line-height: 20px; padding: 0 5px; } .ant-form-item-prompt { display: block; margin: 0 auto; text-align: right; white-space: normal; line-height: 20px; padding: 0 14px 0 5px; font-size: 16px; color: rgba(0, 0, 0, 0.85); } .prompt-red { color: #f5222d !important; } .ant-form-item-radio { &::v-deep(label) { display: inline !important; } } &::v-deep(.ant-checkbox + span) { padding-right: 0 !important; } } ::v-deep(.ant-form-item-control-wrapper) { min-height: 40px; } } .ant-form-long-label { tr td { &:nth-child(2n + 1) { // width: 200px !important; } } } .ant-collapse { border-top: 1px solid #d9d9d9; border-bottom: unset; border-left: unset; border-right: unset; width: 90%; margin: auto; & > .ant-collapse-item { border-bottom: unset; /*& > .ant-collapse-content{*/ /* border-top: 1px solid #d9d9d9;*/ /* border-bottom: 1px solid #d9d9d9;*/ /* border-radius: 4px;*/ /*}*/ &::v-deep(.ant-collapse-content) { border-top: unset; } } } .textarea-wrapper { position: relative; display: block; .m-textarea { padding: 8px 12px; height: 100%; } .m-count { color: #808080; background: #fff; position: absolute; font-size: 12px; bottom: 12px; right: 12px; line-height: 16px; } } .ant-spin-loading { width: 100vw; height: 100vh; display: block; background-color: rgba(0, 0, 0, 0.5); position: fixed; top: 0; left: 0; z-index: 99; } .apply-block { display: flex; align-items: center; .dynamic-delete-button { cursor: pointer; position: relative; font-size: 24px; color: #999; transition: all 0.3s; } .dynamic-delete-button:hover { color: #777; } .dynamic-delete-button[disabled] { cursor: not-allowed; opacity: 0.5; } div { flex: 1; } } .btn-group { display: flex; align-items: center; justify-content: right; width: 90%; margin: 0 auto 20px; button { margin-left: 10px; } } .ant-form-budget-border { border-bottom: 1px solid #d9d9d9; margin-left: -1px; } .budget-box { height: 100%; overflow: hidden; display: flex; flex: 1; flex-direction: column; } .budget-record { width: 100%; height: 100%; overflow: auto; display: flex; justify-content: center; background: #fff; } .budget-record-table { width: 90%; //调整页面表格宽度 // min-width: 840px; padding: 16px; } .budget-record-table-title { margin-bottom: 20px; text-align: center; white-space: pre-wrap; } .header_sd-header_common.ant-layout-header { padding: 0 20px 0 20px; color: #fff; background-image: linear-gradient(90deg, #1890ff 0%, #0162eb 100%); height: 64px; line-height: 64px; } .header_sd-header_common { z-index: 1; } .ant-layout-header { background: #001529; } .ant-layout-header, .ant-layout-footer { flex: 0 0 auto; } header { display: block; } .ant-layout, .ant-layout * { box-sizing: border-box; } .left_sd-header_common { float: left; height: 100%; } .right_sd-header_common { float: right; height: 100%; } .logo_sd-webflow_webflow h3 { color: #fff; } .header_sd-header_common .ant-btn-link { color: #fff; } .button_sd-webflow-button_webflow { max-width: 100%; } </style> 检查代码,针对分值上限设置的校验规则并未生效,请检查代码并修改
07-31
<think>我们正在讨论如何在Vue删除URL中的某个参数。根据提供的引用,有几种方法可以实现:1.使用`window.history.replaceState`直接操作浏览器历史记录的URL(引用[1])2.使用VueRouter的`replace`方法,通过更新路由的query对象来删除参数(引用[2][3][5])注意:直接操作URL字符串(如引用[1])可能不是最佳实践,因为它绕过了VueRouter。推荐使用VueRouter提供的方法。步骤:方法一:使用VueRouter的`replace`方法(推荐)-复制当前路由的查询参数对象(避免直接修改$route.query,因为它是只读的)-删除需要移除的参数-使用`$router.replace`更新路由,该方法不会添加新的历史记录,而是替换当前记录。方法二:使用`window.history.replaceState`(不推荐,除非有特殊原因)-构建新的URL字符串(去除指定参数)-使用`window.history.replaceState(null,null,newUrl)`替换当前URL根据引用[3]和[5]的示例,我们更倾向于使用VueRouter的方法。具体代码示例(方法一):假设我们要删除参数名为`reportCoreId`的参数(引用[3]):```javascript//在Vue组件中methods:{removeQueryParam(paramName){//复制当前查询参数constquery={...this.$route.query};//如果存在该参数,则删除if(query.hasOwnProperty(paramName)){deletequery[paramName];//使用router.replace更新路由,不添加历史记录this.$router.replace({query});}}}```如果要删除多个参数,可以循环删除。另外,引用[2]和[5]也展示了类似的方法:```javascript//删除所有参数(保留路径)this.$router.replace({path:'/example'});//或者删除特定参数,保留其他参数constquery={...this.$route.query};deletequery.id;this.$router.replace({query});```注意:如果同时有path和query,可以这样写:`this.$router.replace({path:'/example',query:{...}})`。如果只提供query,则会保持当前路径。问题:用户可能想要删除一个或多个参数,同时保留其他参数。因此,我们可以总结如下:在Vue中,使用VueRouter删除URL中的某个参数,推荐使用以下步骤:1.复制当前路由的查询参数对象(因为$route.query是只读的)2.删除目标参数3.使用`$router.replace`(或`$router.push`,但replace不会产生历史记录)更新路由示例代码:```javascript//删除单个参数,例如'a'letquery={...this.$route.query};if(query.a){deletequery.a;this.$router.replace({query});//保持当前路径,只改变查询参数}```如果要删除多个参数,可以:```javascriptconstparamsToRemove=['a','b','c'];letquery={...this.$route.query};paramsToRemove.forEach(param=>{if(query[param]){deletequery[param];}});this.$router.replace({query});```注意事项:-使用`replace`不会在浏览器历史记录中新增记录,而是替换当前记录。如果希望用户能通过后退按钮返回,可以使用`push`,但通常删除参数不需要保留历史。-如果删除参数后,query对象为空,那么URL中的?及其后面的参数都会被去除。根据引用[1]中的方法(直接操作URL):```javascript//假设有一个工具函数getnewurl,用于从当前URL中删除参数'a'leturl=this.getnewurl('a');window.history.replaceState(null,null,url);```但是这种方法需要自己处理URL字符串,而且可能不依赖于VueRouter的状态管理,因此不推荐。结论:在Vue项目中,使用VueRouter提供的方法更符合框架的设计,且易于维护。生成相关问题:1.Vue中如何添加URL参数?2.VueRouter的push和replace方法有什么区别?3.如何监听URL参数的变化?4.Vue中如何获取URL参数?5.Vue项目中,如何同时删除多个URL参数?</think>在 Vue删除 URL 参数,推荐使用 Vue Router 提供的方法。以下是两种常用方式: ### 方法一:使用 Vue Router 的 `replace()`(推荐) ```javascript // 在 Vue 组件中 removeParam(paramName) { // 1. 复制当前查询参数 const newQuery = { ...this.$route.query }; // 2. 删除目标参数 if (newQuery[paramName]) { delete newQuery[paramName]; } // 3. 替换当前路由(不产生历史记录) this.$router.replace({ query: newQuery // 保留其他参数 }); // 若需同时删除所有参数: // this.$router.replace({ path: this.$route.path }); } ``` ### 方法二:使用 History API(原生) ```javascript removeParam(paramName) { // 1. 创建新 URL 对象 const url = new URL(window.location.href); // 2. 删除参数 url.searchParams.delete(paramName); // 3. 替换 URL(不刷新页面) window.history.replaceState(null, null, url.toString()); } ``` ### 使用示例 ```javascript // 删除单个参数(如 reportId) this.removeParam('reportId'); // 删除多个参数 ['param1', 'param2'].forEach(p => this.removeParam(p)); ``` ### 关键说明 1. **`router.replace()` vs `router.push()`** - `replace()`:替换当前路由,**不产生新历史记录**(后退直接跳过) - `push()`:新增历史记录(后退会返回带参数的页面) 2. **参数处理逻辑** ```javascript // 保留其他参数 const newQuery = { ...this.$route.query }; // 浅拷贝 delete newQuery.targetParam; // 删除指定参数 ``` 3. **Vue Router 规范** - 直接修改 `$route.query` 无效(它是只读的) - 必须通过 `$router.replace/push` 更新路由[^3][^5] ### 注意事项 - 删除参数后页面**不会自动刷新**,需手动处理数据重置 - 使用 `$router.replace` 时,Vue Router 会触发**导航守卫** - 若需监听参数变化,可在 `watch` 中监测 `$route.query` --- ### 相关问题 1. Vue 中如何动态添加 URL 参数? 2. 使用 `router.replace()` 和 `router.push()` 有什么区别? 3. 如何监听 Vue Router 的 URL 参数变化? 4. Vue 路由传参有哪些方式(params vs query)? 5. 如何防止用户手动修改 URL 参数导致页面异常?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

仙人掌上的刺猬

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

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

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

打赏作者

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

抵扣说明:

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

余额充值