vue3+antd-vue实现增改弹窗
对于前端来说,在后台系统中最常见的需求,就是基于表单表格的正删改查。对于增和改,需要实现弹框组件。代码如下:
<template>
<div>
<a-modal
:title="modalTitle"
v-model:visible="visible"
cancelText="取消"
okText="提交"
>
<a-form
:model="formState"
name="classForm"
ref="formRef"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item
label="学校名称"
name="schoolId"
:rules="[{ required: true, message: '请选择学校', trigger: 'blur' }]"
>
<a-select
allowClear
:options="[
{ label: '学校1', value: 1 },
{ label: '学校2', value: 2 }
]"
placeholder="选择学校"
v-model:value="formState.schoolId"
></a-select>
</a-form-item>
<a-form-item
label="班课名称"
name="courseName"
:rules="[{ required: true, message: '请输入班课名称' }]"
>
<a-input
allowClear
placeholder="输入班课名称"
v-model:value="formState.courseName"
></a-input>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup>
import { reactive, ref, nextTick, computed } from 'vue'
const ModalOpenType = {
ADD: 0,
EDIT: 1
}
const visible = ref(false)
const formRef = ref(null)
const operationName= ref('')
const props = defineProps(['name'])
const modalTitle = computed(() => operationName.value + props.name)
const resetForm = () => {
formRef.value.clearValidate()
formRef.value.resetFields()
}
const open = (type, id) => {
visible.value = true
nextTick(async () => {
resetForm()
console.log(props)
if (type === ModalOpenType.EDIT) {
operationName.value = '编辑'
const rowData = await getRowById(id)
replaceFormFieldsValues(rowData)
} else {
operationName.value = '新增'
}
})
}
const getRowById = id => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
schoolId: 2,
courseName: 'qwe'
})
}, 300)
})
}
const formState = reactive({
schoolId: null,
courseName: ''
})
const replaceFormFieldsValues = data => {
Object.keys(data).forEach(key => {
formState[key] = data[key]
})
}
defineExpose({
open
})
</script>
<style lang="" scoped></style>
使用方法:
模板使用组件
<ClassModal ref="classModal" :name="`班课`"/>
控制打开弹窗
<a-button size="small" type="primary" style="margin-right: 10px" @click="openModal(ModalOpenType.EDIT, record.id)">编辑</a-button>
js
const classModal = ref(null)
function openModal(type) {
classModal.value.open(type)
}
作者:charles1600
链接:https://www.jianshu.com/p/735d173f7421
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。