el-upload组件图片上传永远在首位
时间: 2023-11-09 20:00:36 浏览: 48
对于el-upload组件,可以通过设置list-type属性来控制上传文件展示的方式。而默认的list-type是text,会将上传的文件信息按照文本的形式展示,因此上传的图片永远在首位。如果需要让图片在最后面,则可以将list-type设置为picture-card或picture,这两种方式会将上传的文件以卡片或缩略图的形式展示,并且新上传的图片会显示在最后面。
相关问题
如何在el-upload组件中使用before-upload钩子函数?
在el-upload组件中使用before-upload钩子函数,可以通过以下步骤实现:
1. 在el-upload组件上添加before-upload属性,并将其值设置为一个函数名,该函数将在上传文件之前被调用。
2. 在Vue的methods选项中定义该函数,并在函数内部编写上传前的逻辑。
下面是一个示例代码:
```html
<template>
<el-upload
action="/upload"
:before-upload="handleBeforeUpload"
>
<el-button slot="trigger" size="small" type="primary">点击上传</el-button>
</el-upload>
</template>
<script>
export default {
methods: {
handleBeforeUpload(file) {
// 在这里编写上传前的逻辑
console.log('上传前的文件信息:', file);
// 返回false可以阻止文件上传
// return false;
}
}
}
</script>
```
在上述代码中,我们在el-upload组件上添加了before-upload属性,并将其值设置为handleBeforeUpload函数名。在handleBeforeUpload函数中,我们可以编写上传前的逻辑,例如打印文件信息或者根据特定条件阻止文件上传。
需要注意的是,如果before-upload函数返回false,将会阻止文件上传。
el-upload上传图片成功后,隐藏继续el-upload组件,只显示已上传的图片
可以通过监听 `on-success` 事件,在事件回调函数中获取上传成功的文件列表,然后将这些文件列表保存到组件的 `file-list` 属性中,最后将 `show-file-list` 属性设置为 `true`,这样组件就会隐藏上传区域,只显示已上传的文件列表。
具体实现代码如下:
```html
<template>
<div>
<el-upload
ref="upload"
class="upload-demo"
:action="uploadUrl"
:on-success="handleSuccess"
:file-list="fileList"
:show-file-list="showFileList"
:auto-upload="false"
:list-type="'picture'"
multiple>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<el-button size="small" type="warning" @click="clearFiles">清空文件</el-button>
</el-upload>
<el-divider></el-divider>
<div v-if="showFileList">
<el-image v-for="(file, index) in fileList" :key="index" :src="file.url" style="margin-right: 20px" :fit="fit" :preview-src-list="previewSrcList"></el-image>
</div>
</div>
</template>
<script>
export default {
data() {
return {
uploadUrl: '/upload',
fileList: [],
showFileList: false,
previewSrcList: [],
fit: 'cover'
}
},
methods: {
handleSuccess(response, file, fileList) {
fileList.forEach(item => {
this.previewSrcList.push(item.url)
})
this.fileList = fileList
this.showFileList = true
},
submitUpload() {
this.$refs.upload.submit()
},
clearFiles() {
this.fileList = []
this.showFileList = false
this.previewSrcList = []
}
}
}
</script>
```
在上面的代码中,我们监听了 `on-success` 事件,并在事件回调函数中获取上传成功的文件列表,然后将这些文件列表保存到 `fileList` 属性中,最后将 `showFileList` 属性设置为 `true`,这样组件就会隐藏上传区域,只显示已上传的文件列表。
同时,我们在显示已上传的文件列表时,通过 `v-for` 指令遍历 `fileList` 数组,使用 `el-image` 组件来显示每个文件的预览图,并通过 `preview-src-list` 属性设置预览图的列表。