结合element plus的el-upload标签,实现上传图片和视频,并支持在线预览和放大
1、html部分
<el-form-item label="活动照片、视频"><el-uploadv-model:file-list="state.photoList":action="state.uploadUrl"accept=".jpg,.png,.jpeg,.mp4,.mov,.avi"list-type="picture-card":limit="10":on-success="handleUpload":class="state.photoList.length === 10 ? 'hideUpload' : ''"><el-icon><Plus /></el-icon><template #file="{ file }"><div><imgv-if="file.name.indexOf('.jpg') > -1|| file.name.indexOf('.png') > -1|| file.name.indexOf('.jpeg') > -1":src="file.url"alt=""class="el-upload-list__item-thumbnail" /><videov-else-if="file.name.indexOf('.mp4') > -1|| file.name.indexOf('.mov') > -1|| file.name.indexOf('.avi') > -1"class="el-upload-list__item-thumbnail"style="width: 100%;height: 100%;"autoplay:src="file.url"><source :src="file.url" type="video/mp4" /><source :src="file.url" type="video/mov" /><source :src="file.url" type="video/avi" /></video><span class="el-upload-list__item-actions"><span class="el-upload-list__item-preview" @click="handlePreview(file)"><el-icon><zoom-in /></el-icon></span><spanv-if="!state.disabledBtn"class="el-upload-list__item-delete"@click="handleRemove(file)"><el-icon><Delete /></el-icon></span></span></div></template></el-upload><el-dialog v-model="state.dialogVisible"><imgw-full:src="state.dialogImageFile.url"alt=""v-if="state.dialogImageFile.name.indexOf('.jpg') > -1|| state.dialogImageFile.name.indexOf('.png') > -1|| state.dialogImageFile.name.indexOf('.jpeg') > -1" /><videov-else-if="state.dialogImageFile.name.indexOf('.mp4') > -1|| state.dialogImageFile.name.indexOf('.mov') > -1|| state.dialogImageFile.name.indexOf('.avi') > -1"w-fullstyle="width: 100%;height: 100%;"controlsautoplay:src="state.dialogImageFile.url"><source :src="state.dialogImageFile.url" type="video/mp4" /><source :src="state.dialogImageFile.url" type="video/mov" /><source :src="state.dialogImageFile.url" type="video/avi" /></video></el-dialog>
</el-form-item>
2、js部分
const state = reactive({photoList: [] as any, // 上传图片dialogVisible: false as boolean,dialogImageFile: '' as any,disabledBtn: false as boolean,
});// 预览图片和视频
const handlePreview = (file: any) => {state.dialogImageFile = file;state.dialogVisible = true;
}
// 删除图片视频
const handleRemove = (file: any) => {state.photoList.map((item: any, index: number) => {if(item.response && item.response.data) {if(item.response.data == file.response?.data || item.response.data == file.url) {state.photoList.splice(index, 1);}} else if(item.url) {if(item.url == file.response?.data || item.url == file.url) {state.photoList.splice(index, 1);}}})
}
// 上传图片
const handleUpload = (res: any) => {if(res.code != 0) {state.photoList.pop()ElMessage.error(res.msg)}
}
3、css部分
<style lang="scss" scoped>:deep(.hideUpload .el-upload--picture-card) {display: none;}:deep(.el-upload--picture-card) {width: 243px;height: 180px;}:deep(.el-upload-list--picture-card .el-upload-list__item) {width: 243px;height: 180px;}
</style>