解析element-ui中upload组件传递文件及其他参数的问题,需要分步骤进行操作。
第一步:引入Element-ui组件
首先需要在Vue项目中引入Element-ui组件:
<template>
<el-upload
class="upload-demo"
ref="upload"
:action="uploadUrl"
:headers="{'Authorization': token}"
:data="{userId:111,userName:'张三'}"
:multiple="true"
:limit="3"
:on-exceed="handleExceed"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
第二步:配置相关参数
要传递文件及其他参数,需要配置相关参数。下面分别说明:
action
必须属性,上传的地址。
<el-upload
:action="uploadUrl">
...
</el-upload>
headers
设置上传的请求头部,有其他需求可自行设置。
<el-upload
:headers="{'Authorization': token}">
...
</el-upload>
data
上传时附带的额外参数,需要使用对象的方式进行传递。
<el-upload
:data="{userId:111,userName:'张三'}">
...
</el-upload>
第三步:处理上传前的判断和回调
before-upload
上传前,判断是否符合要求。不能超过500kb,并且只能上传jpeg、png文件。
<el-upload
:before-upload="beforeUpload">
...
</el-upload>
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 0.5;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 500KB!');
}
return isJPG && isLt2M;
}
on-success
上传成功后回调函数。
<el-upload
:on-success="handleSuccess">
...
</el-upload>
handleSuccess(res, file) {
console.log(res); // 成功返回值
console.log(file); // 文件对象
}
示例说明
示例一:处理上传时需要传递Vue组件中的数据
我们可以使用Vue的ref来获取组件的实例,然后使用实例中的数据。
<template>
<el-upload
ref="upload"
:data="{userId: userId, userName: userName}">
...
</el-upload>
</template>
<script>
export default {
data() {
return {
userId: '111',
userName: '张三'
}
},
methods: {
handleUpload() {
// 调用实例方法,触发上传操作
this.$refs.upload.submit();
}
}
}
</script>
示例二:处理批量上传
可以通过配置multiple和limit来实现。
<template>
<el-upload
:multiple="true"
:limit="3">
...
</el-upload>
</template>
以上就是解析Element-ui中upload组件传递文件及其他参数的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:解析element-ui中upload组件传递文件及其他参数的问题 - Python技术站