使用Vue 3 + TypeScript 实现可动态添加行的表格表单
<template>
<el-form :model="formData" ref="formRef" label-width="100px">
<el-table :data="formData.rows" border>
<el-table-column label="序号" width="70">
<template #default="{ $index }">
{{ $index + 1 }}
</template>
</el-table-column>
<el-table-column label="名称" prop="name">
<template #default="{ row }">
<el-input v-model="row.name"></el-input>
</template>
</el-table-column>
<el-table-column label="图片" prop="image">
<template #default="{ row }">
<el-upload
action="#"
list-type="picture-card"
:auto-upload="false"
:on-change="(file) => handleImageChange(file, row)"
>
<i class="el-icon-plus"></i>
</el-upload>
</template>
</el-table-column>
<el-table-column label="视频" prop="video">
<template #default="{ row }">
<el-upload
action="#"
:auto-upload="false"
:on-change="(file) => handleVideoChange(file, row)"
>
<el-button size="small" type="primary">上传视频</el-button>
</el-upload>
</template>
</el-table-column>
<el-table-column label="备注" prop="remark">
<template #default="{ row }">
<el-input v-model="row.remark" type="textarea"></el-input>
</template>
</el-table-column>
</el-table>
<el-button @click="addRow" :disabled="formData.rows.length >= 6" style="margin-top: 10px;">
添加行
</el-button>
<el-button type="primary" @click="submitForm" style="margin-top: 20px;">
提交
</el-button>
</el-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadFile } from 'element-plus'
interface RowData {
name: string
image: string
video: string
remark: string
}
const formRef = ref()
const formData = reactive({
rows: [] as RowData[]
})
const addRow = () => {
if (formData.rows.length < 6) {
formData.rows.push({
name: '',
image: '',
video: '',
remark: ''
})
}
}
const handleImageChange = (file: UploadFile, row: RowData) => {
row.image = URL.createObjectURL(file.raw!)
}
const handleVideoChange = (file: UploadFile, row: RowData) => {
row.video = URL.createObjectURL(file.raw!)
}
const submitForm = async () => {
try {
await formRef.value.validate()
// 调用后端API
const response = await fetch('/api/addRows', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData.rows),
})
if (response.ok) {
ElMessage.success('提交成功')
// 重置表单
formData.rows = []
} else {
ElMessage.error('提交失败')
}
} catch (error) {
console.error('表单验证失败:', error)
ElMessage.error('表单验证失败,请检查输入')
}
}
</script>
这个示例实现了以下功能:
- 使用
el-form
和el-table
来创建一个可编辑的表格。 - 表格包含序号、名称、图片、视频和备注五列。
- 使用
el-upload
组件处理图片和视频的上传。 - 通过
addRow
函数实现动态添加行,最多可添加6行。 - 使用
submitForm
函数处理表单提交,包括表单验证和调用后端API。
注意事项:
- 这个示例中,图片和视频上传使用了
URL.createObjectURL
来创建本地预览URL。在实际应用中,你可能需要将文件上传到服务器,并使用服务器返回的URL。 - 后端API的URL(
/api/addRows
)需要根据实际后端接口来调整。 - 处理大文件(如视频)时,可能需要考虑分片上传等优化措施。
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓