opt: 格式化json优化

This commit is contained in:
2026-02-04 14:20:44 +08:00
parent a24e254fc9
commit 99deee4876

View File

@@ -18,12 +18,31 @@
<a-input v-model:value="formData.apiMethod" placeholder="请输入请求方法GET, POST, PUT, DELETE" allow-clear />
</a-form-item>
</a-col>
<a-col :span="12">
<a-col :span="24">
<a-form-item label="返回数据:" name="responseJson">
<a-input v-model:value="formData.responseJson" placeholder="请输入返回的JSON数据" allow-clear />
<div style="position: relative">
<a-textarea
v-model:value="formData.responseJson"
placeholder="请输入返回的JSON数据"
:rows="10"
allow-clear
style="font-family: 'Courier New', monospace"
/>
<a-button
type="link"
size="small"
style="position: absolute; top: 8px; right: 8px; z-index: 1"
@click="formatJson"
>
<template #icon>
<AlignLeftOutlined />
</template>
格式化
</a-button>
</div>
</a-form-item>
</a-col>
<a-col :span="12">
<a-col :span="24">
<a-form-item label="是否启用" name="isEnabled">
<a-radio-group
v-model:value="formData.isEnabled"
@@ -42,9 +61,10 @@
</template>
<script setup name="mockConfigForm">
import { message } from 'ant-design-vue'
import { AlignLeftOutlined } from '@ant-design/icons-vue'
import tool from '@/utils/tool'
import { cloneDeep } from 'lodash-es'
import { required } from '@/utils/formRules'
import mockConfigApi from '@/api/mock/mockConfigApi'
// 抽屉状态
const open = ref(false)
@@ -68,6 +88,15 @@
} else if (recordData.isEnabled === 1 || recordData.isEnabled === 0) {
recordData.isEnabled = String(recordData.isEnabled)
}
// 如果有JSON数据尝试格式化显示
if (recordData.responseJson) {
try {
const jsonObj = JSON.parse(recordData.responseJson)
recordData.responseJson = JSON.stringify(jsonObj, null, 2)
} catch (e) {
// 如果解析失败,保持原样
}
}
formData.value = Object.assign({}, recordData)
} else {
// 新增时默认启用:'1'
@@ -81,9 +110,22 @@
formData.value = {}
open.value = false
}
// 默认要校验的
const formRules = {
// 格式化JSON
const formatJson = () => {
if (!formData.value.responseJson) {
message.warning('请先输入JSON数据')
return
}
try {
const jsonObj = JSON.parse(formData.value.responseJson)
formData.value.responseJson = JSON.stringify(jsonObj, null, 2)
message.success('格式化成功')
} catch (e) {
message.error('JSON格式错误请检查输入')
}
}
// 默认要校验的
const formRules = {}
// 验证并提交数据
const onSubmit = () => {
formRef.value
@@ -97,6 +139,17 @@
} else if (formDataParam.isEnabled === '0') {
formDataParam.isEnabled = 0
}
// 提交前压缩JSON去除格式化的空格和换行确保后端能正常解析
if (formDataParam.responseJson) {
try {
const jsonObj = JSON.parse(formDataParam.responseJson)
formDataParam.responseJson = JSON.stringify(jsonObj)
} catch (e) {
message.error('JSON格式错误请检查后重试')
submitLoading.value = false
return
}
}
mockConfigApi
.mockConfigSubmitForm(formDataParam, formDataParam.id)
.then(() => {