ref 调整表单编辑和axios参数处理机制

This commit is contained in:
xxm
2022-10-11 17:34:45 +08:00
parent 148d37ffae
commit d46cfd8180
8 changed files with 137 additions and 55 deletions

View File

@@ -5,7 +5,9 @@ import {
Input,
InputNumber,
Empty,
Popconfirm,
Select,
SelectOption,
Switch,
Tree,
TreeSelect,
@@ -45,7 +47,9 @@ export function registerGlobComp(app: App) {
app.use(DatePicker)
app.use(TimePicker)
app.use(Empty)
app.use(Popconfirm)
app.use(Select)
app.use(SelectOption)
app.use(Switch)
app.use(Tree)
app.use(TreeSelect)

View File

@@ -1,7 +1,7 @@
/**
* 表单类型
* 表单编辑类型
*/
export enum FormType {
export enum FormEditType {
Add,
Edit,
Show,

View File

@@ -1,5 +1,5 @@
import { reactive, toRefs } from 'vue'
import { FormType } from "/@/enums/formTypeEnum";
import { FormEditType } from '/@/enums/formTypeEnum'
export default function () {
const model = reactive({
@@ -18,23 +18,23 @@ export default function () {
editable: false,
addable: false,
showable: false,
type: FormType.Add,
formEditType: FormEditType.Add,
})
// 状态
const { labelCol, wrapperCol, title, modalWidth, confirmLoading, visible, editable, addable, showable, type } = toRefs(model)
const { labelCol, wrapperCol, title, modalWidth, confirmLoading, visible, editable, addable, showable, formEditType } = toRefs(model)
function initFormModel(record, fromType: FormType, ...vars) {
type.value = fromType
function initFormModel(record, editType: FormEditType, ...vars) {
formEditType.value = editType
visible.value = true
if (type.value === FormType.Add) {
if (formEditType.value === FormEditType.Add) {
addable.value = true
title.value = '新增'
}
if (type.value === FormType.Edit) {
if (formEditType.value === FormEditType.Edit) {
editable.value = true
title.value = '修改'
}
if (type.value === FormType.Show) {
if (formEditType.value === FormEditType.Show) {
showable.value = true
title.value = '查看'
}
@@ -64,7 +64,7 @@ export default function () {
editable,
addable,
showable,
type,
formEditType,
initFormModel,
handleCancel,
search,

View File

@@ -33,29 +33,26 @@ const transform: AxiosTransform = {
transformResponseHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
const { t } = useI18n()
const { isTransformResponse, isReturnNativeResponse } = options
// 是否返回原生响应头 比如:需要获取响应头时使用该属性
if (isReturnNativeResponse) {
return res
}
// 不进行任何处理,直接返回
// 用于页面代码可能需要直接获取codedatamessage这些信息时开启
if (!isTransformResponse) {
return res.data
}
// if (!isTransformResponse) {
// return res.data
// }
// 错误的时候返回
// 获取请求头重的数据
const rawData = res.data
if (!rawData) {
// return '[HTTP] Request has no return value';
throw new Error(t('sys.api.apiRequestFailed'))
throw new Error('请求出错,请稍候重试')
}
// 这里 codedatamessage为 后台统一的字段,需要在 types.ts内修改为项目自己的接口返回格式
const { code, data, message } = rawData
const { code, msg, traceId } = rawData
// 这里逻辑可以根据项目进行修改
const hasSuccess = rawData && Reflect.has(rawData, 'code') && code === ResultEnum.SUCCESS
if (hasSuccess) {
return data
return rawData
}
// 在此处根据自己项目的实际情况对不同的code执行不同的操作
@@ -63,14 +60,14 @@ const transform: AxiosTransform = {
let timeoutMsg = ''
switch (code) {
case ResultEnum.TIMEOUT:
timeoutMsg = t('sys.api.timeoutMessage')
timeoutMsg = '登录超时,请重新登录!'
const userStore = useUserStoreWithOut()
userStore.setToken(undefined)
userStore.logout(true)
break
default:
if (message) {
timeoutMsg = message
if (msg) {
timeoutMsg = msg
}
}
@@ -81,8 +78,8 @@ const transform: AxiosTransform = {
} else if (options.errorMessageMode === 'message') {
createMessage.error(timeoutMsg)
}
throw new Error(timeoutMsg || t('sys.api.apiRequestFailed'))
console.error('TraceId:', traceId)
throw new Error(timeoutMsg || '请求出错,请稍候重试')
},
// 请求之前处理config
@@ -115,9 +112,9 @@ const transform: AxiosTransform = {
config.data = data
config.params = params
} else {
// 非GET请求如果没有提供data则将params视为data
config.data = params
config.params = undefined
// 非GET请求如果没有提供data则将params视为data (去除, 非GET也会进行普通参数请求)
// config.data = params
// config.params = undefined
}
if (joinParamsToUrl) {
config.url = setObjToUrlParams(config.url as string, Object.assign({}, config.params, config.data))
@@ -221,7 +218,7 @@ function createAxios(opt?: Partial<CreateAxiosOptions>) {
joinPrefix: true,
// 是否返回原生响应头 比如:需要获取响应头时使用该属性
isReturnNativeResponse: false,
// 需要对返回数据进行处理
// 需要对返回数据进行处理 (无效)
isTransformResponse: false,
// post请求的时候添加参数到url
joinParamsToUrl: false,
@@ -240,7 +237,7 @@ function createAxios(opt?: Partial<CreateAxiosOptions>) {
// 是否携带token
withToken: true,
retryRequest: {
isOpenRetry: true,
isOpenRetry: false,
count: 5,
waitTime: 100,
},

View File

@@ -25,7 +25,7 @@ export const get = (id) => {
/**
* 添加
*/
export const add = (obj) => {
export const add = (obj: Client) => {
return defHttp.post({
url: '/client/add',
data: obj,
@@ -35,13 +35,49 @@ export const add = (obj) => {
/**
* 更新
*/
export const update = (obj) => {
export const update = (obj: Client) => {
return defHttp.post({
url: '/client/update',
data: obj,
})
}
/**
* 删除
*/
export const del = (id) => {
return defHttp.delete({
url: '/client/delete',
params: { id },
})
}
/**
* 查询全部
*/
export const findAll = () => {
return defHttp.get<Result<Array<Client>>>({
url: '/client/findAll',
})
}
/**
* 编码是否被使用
*/
export const existsByCode = (code: string) => {
return defHttp.get<Result<boolean>>({
url: '/client/existsByCode',
method: 'GET',
})
}
export const existsByCodeNotId = (code: string, id: number) => {
return defHttp.get<Result<boolean>>({
url: '/client/existsByCodeNotId',
method: 'GET',
params: { code, id },
})
}
/**
* 实体类接口
*/

View File

@@ -56,11 +56,11 @@
</template>
<script lang="ts" setup>
import { nextTick, reactive } from 'vue'
import { nextTick, reactive, ref } from 'vue'
import useFormEdit from '/@/hooks/bootx/useFormEdit'
import { Client, get } from './Client.api'
import { add, Client, get, update } from './Client.api'
import { useForm } from 'ant-design-vue/lib/form'
import { FormType } from '/@/enums/formTypeEnum'
import { FormEditType } from '/@/enums/formTypeEnum'
const {
initFormModel,
@@ -74,9 +74,10 @@
visible,
editable,
showable,
type,
formEditType,
} = useFormEdit()
let form = reactive({
const loginTypes = ref([])
const form = ref({
id: null,
code: '',
name: '',
@@ -94,23 +95,26 @@
name: [{ required: true, message: '请输入应用名称' }],
enable: [{ required: true, message: '请选择启用状态' }],
})
function validateCode(rule, value, callback) {}
// 表单
const { resetFields, validate, validateInfos } = useForm(form, rules)
// 事件
const emits = defineEmits(['ok'])
function validateCode(rule, value, callback) {}
// 入口
function init(id, editType: FormType) {
function init(id, editType: FormEditType) {
initFormModel(id, editType)
resetForm()
getInfo(id, editType)
}
// 获取信息
function getInfo(id, type: FormType) {
function getInfo(id, editType: FormEditType) {
// this.initLoginTypes()
if ([FormType.Edit, FormType.Show].includes(type)) {
if ([FormEditType.Edit, FormEditType.Show].includes(editType)) {
confirmLoading.value = true
get(id).then(({ data }) => {
form = reactive(data)
form.value = data
confirmLoading.value = false
})
} else {
@@ -118,11 +122,17 @@
}
}
// 保存
async function handleOk() {
validate().then(() => {
function handleOk() {
validate().then(async () => {
confirmLoading.value = true
console.log(form)
if (formEditType.value === FormEditType.Add) {
await add(form.value)
} else if (formEditType.value === FormEditType.Edit) {
await update(form.value)
}
confirmLoading.value = false
handleCancel()
emits('ok')
})
}

View File

@@ -4,14 +4,14 @@
<b-query :query-params="model.queryParam" :fields="fields" @query="queryPage" @reset="resetQueryParams" />
</div>
<div class="m-3 p-3 bg-white">
<vxe-toolbar>
<vxe-toolbar ref="vxeToolbar" :refresh="{ query: queryPage }">
<template #buttons>
<a-space>
<a-button type="primary" @click="add">新建</a-button>
</a-space>
</template>
</vxe-toolbar>
<vxe-table row-id="id" :data="pagination.records" :loading="loading">
<vxe-table ref="vxeTable" row-id="id" :data="pagination.records" :loading="loading">
<vxe-column type="seq" width="60" />
<vxe-column field="code" title="编码" />
<vxe-column field="name" title="名称" />
@@ -29,6 +29,21 @@
</vxe-column>
<vxe-column field="description" title="描述" />
<vxe-column field="createTime" title="创建时间" />
<vxe-column fixed="right" width="150" :showOverflow="false" title="操作">
<template #default="{ row }">
<span>
<a href="javascript:" @click="show(row)">查看</a>
</span>
<a-divider type="vertical" />
<span>
<a href="javascript:" @click="edit(row)">编辑</a>
</span>
<a-divider type="vertical" />
<a-popconfirm title="是否删除" @confirm="remove(row)" okText="是" cancelText="否">
<a href="javascript:" style="color: red">删除</a>
</a-popconfirm>
</template>
</vxe-column>
</vxe-table>
<vxe-pager
size="medium"
@@ -45,20 +60,22 @@
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { page } from './Client.api'
import { del, page } from './Client.api'
import useTablePage from '/@/hooks/bootx/useTablePage'
import ClientEdit from './ClientEdit.vue'
import BQuery from '/@/components/Bootx/Query/BQuery.vue'
import { STRING } from '/@/components/Bootx/Query/SuperQueryCode'
import { FormEditType } from '/@/enums/formTypeEnum'
import { useMessage } from '/@/hooks/web/useMessage'
// 使用hooks
const { handleTableChange, pageQueryResHandel, resetQueryParams, pagination, pages, model, loading } = useTablePage(queryPage)
const clientEdit = ref()
// 查询条件z
// 查询条件
const fields = [
{ field: 'code', type: STRING, name: '编码', placeholder: '请输入终端编码' },
{ field: 'name', type: STRING, name: '名称', placeholder: '请输入终端名称' },
{ field: 'code', formType: STRING, name: '编码', placeholder: '请输入终端编码' },
{ field: 'name', formType: STRING, name: '名称', placeholder: '请输入终端名称' },
]
const clientEdit = ref()
onMounted(() => {
queryPage()
@@ -76,7 +93,24 @@
}
// 新增
function add() {
clientEdit.value.init(null, '')
clientEdit.value.init(null, FormEditType.Add)
}
// 查看
function edit(record) {
clientEdit.value.init(record.id, FormEditType.Edit)
}
// 查看
function show(record) {
clientEdit.value.init(record.id, FormEditType.Show)
}
// 删除
const { notification } = useMessage()
function remove(record) {
del(record.id).then(() => {
notification.success({ message: '删除成功' })
})
queryPage()
}
</script>

3
types/axios.d.ts vendored
View File

@@ -39,7 +39,8 @@ export interface RetryRequest {
export interface Result<T = any> {
code: number
type: 'success' | 'error' | 'warning'
message: string
msg: string
traceId: string | null | undefined
data: T
}