先放代码,下面做字段详细解释
以下使用场景为:修改表单数据,表单中包含图片。
js
<el-upload
:action="uploadImg"
multiple
:headers="headers"
:on-success="(response, file, fileList) => successUpload(item.name,response,file,fileList)"
:on-error="errorUpload"
:limit="4"
list-type="picture-card"
:file-list="localFormData[item.name]"
:on-remove="(file, fileList) => handleRemove(file, fileList, item.name)"
:on-preview="handlePictureCardPreview">
//自定义图标/提示文字
<img src="/images/ticketForm/camera.png" />
<div class="add-picture">
<el-icon><Plus /></el-icon>
<span>添加图片</span>
</div>
</el-upload>
<el-dialog v-model="dialogVisible">
<img w-full :src="dialogImageUrl" alt="Preview Image" class="img-box" />
</el-dialog>
//js
import { uploadImg } from '@/api/system/system'//上传图片的接口
import { useUser } from '@/store/user'
const userStore = useUser()
const token = userStore.getToken()
const headers = ref({
"x-access-token": token
})
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const successUpload = (name, response, file, fileList) => {
localFormData[name].push(file.response.result);//localFormData存储表单数据的对象
}
const errorUpload = (error) => {
console.log(error);
}
// 移除图片
const handleRemove = (file, files, name) => {
files.forEach(item => {
if (item.response && item.response.length > 0) {
item = item.response.result
}
})
localFormData[name] = JSON.parse(JSON.stringify(files));
}
//放大展示
const handlePictureCardPreview = (file) => {
dialogImageUrl.value = file.url
dialogVisible.value = true
}
先讲一下这里提交包含图片的表单的逻辑:
1、先上传图片到服务器,服务器会返回一个地址.
2、把服务器返回的地址存放到存放表单的变量中,再提交表单数据即可。
upload组件相关属性解释:
action:上传图片的接口地址。
multiple:是否支持多选文件。
headers:请求接口的请求头。
on-success:文件上传成功的回调。
on-error:文件上传失败时的回调。
on-remove:文件移除时的回调。
on-preview:点击文件列表中已上传的文件时的回调。
limit:最大上传文件数。
list-type:文件列表的类型。
file-list:默认上传文件(等于v-model:file-list可以设置默认上传的图片,或者用来展示该字段原有的图片.如果只是新增表单可以不用写该字段,这里是用来修改表单数据时,展示原有数据使用)。
注:
file-list展示的数据格式为(结构不对会显示不出来):
{ name: '', url: ''},{ name: '', url: ''}\] (name根据情况传入,url必须有) 此部分代码localFormData\[name\]为表单数据存储的对象,使用时根据实际情况修改即可。