用vue3和elementplus写一段代码,要求能上传文件,并把文件名展示在弹窗中
时间: 2024-03-17 21:41:05 浏览: 67
好的,以下是符合您要求的代码示例:
```html
<template>
<div>
<el-button @click="dialogVisible = true">上传文件</el-button>
<el-dialog :visible.sync="dialogVisible" title="上传文件" width="30%">
<el-upload
class="upload-demo"
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-progress
class="progress"
:stroke-width="4"
:percentage="uploadPercent"
:color="uploadPercent === 100 ? '#00bfff' : '#409eff'"
:status="uploadPercent === 100 ? 'success' : ''"
:text-inside="true"
/>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" :disabled="!uploadDone" @click="submitForm">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { ref } from 'vue'
import { ElUpload, ElButton, ElDialog, ElProgress } from 'element-plus'
export default {
components: { ElUpload, ElButton, ElDialog, ElProgress },
setup() {
const dialogVisible = ref(false)
const uploadDone = ref(false)
const uploadPercent = ref(0)
const fileName = ref('')
const beforeUpload = (file) => {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt500K = file.size / 1024 < 500
if (!isJPG) {
this.$message.error('上传文件只能是 JPG/PNG 格式!')
return false
}
if (!isLt500K) {
this.$message.error('上传文件大小不能超过 500KB!')
return false
}
return true
}
const handleSuccess = (response, file) => {
uploadDone.value = true
fileName.value = file.name
}
const submitForm = () => {
console.log('提交文件:', fileName.value)
dialogVisible.value = false
}
return {
dialogVisible,
uploadDone,
uploadPercent,
beforeUpload,
handleSuccess,
submitForm,
fileName
}
}
}
</script>
```
这段代码使用了Element Plus中的`el-upload`组件实现文件上传功能,上传成功后会将`uploadDone`和`fileName`的值进行更新。弹窗的展示使用了`el-dialog`组件,其中`visible`属性通过`v-model`与`dialogVisible`变量进行双向绑定。最后,当用户点击确定按钮时,会将文件名传递给后端进行处理。
阅读全文