el-upload二次封装
时间: 2023-10-28 19:02:10 浏览: 109
对于el-upload的二次封装,你可以按照以下步骤进行:
1. 创建一个新的组件,例如UploadWrapper.vue。
2. 在UploadWrapper.vue中引入el-upload组件:
```javascript
<template>
<el-upload></el-upload>
</template>
<script>
import { Upload } from 'element-ui';
export default {
components: {
'el-upload': Upload
},
}
</script>
```
3. 在UploadWrapper.vue中,将el-upload的props和事件传递给封装组件:
```javascript
<template>
<el-upload
:action="action"
:headers="headers"
:data="data"
:file-list="fileList"
:multiple="multiple"
:before-upload="beforeUpload"
:on-success="onSuccess"
:on-remove="onRemove"
></el-upload>
</template>
<script>
// ...
export default {
// ...
props: {
action: String,
headers: Object,
data: Object,
fileList: Array,
multiple: Boolean
},
methods: {
beforeUpload(file) {
this.$emit('before-upload', file);
},
onSuccess(response, file, fileList) {
this.$emit('on-success', response, file, fileList);
},
onRemove(file, fileList) {
this.$emit('on-remove', file, fileList);
}
}
}
</script>
```
4. 在父组件中使用封装组件UploadWrapper.vue:
```javascript
<template>
<upload-wrapper
:action="action"
:headers="headers"
:data="data"
:file-list="fileList"
:multiple="multiple"
@before-upload="beforeUpload"
@on-success="onSuccess"
@on-remove="onRemove"
></upload-wrapper>
</template>
<script>
import UploadWrapper from './UploadWrapper.vue'
export default {
components: {
'upload-wrapper': UploadWrapper
},
data() {
return {
action: 'your-action-url',
headers: { // headers配置 },
data: { // 请求携带的额外参数 },
fileList: [], // 文件列表
multiple: true // 是否支持多选
}
},
methods: {
beforeUpload(file) {
// 文件上传前的操作
},
onSuccess(response, file, fileList) {
// 文件上传成功的操作
},
onRemove(file, fileList) {
// 文件移除的操作
}
}
}
</script>
```
这样,你就完成了el-upload的二次封装。在父组件中,通过props传入el-upload的配置项和事件,并在UploadWrapper组件中进行处理和触发相应的事件。同时可以根据需要自定义一些额外的功能和样式。
阅读全文