业务中有需要使用上传图片的场景,于是打算写一个通用的组件。
上传时会带额外的参数path字段,用于告诉后端是哪个模块下,比如logo、头像等。
话不多说,直接撸代码吧
<template>
<div>
<el-upload
class="upload-demo"
action="1122"
list-type="picture-card"
:before-upload="beforeUpload"
:on-success="onUploadSuccess"
:on-preview="handlePictureCardPreview"
:file-list="fileList"
:http-request="doUpload"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="file" slot-scope="{file}">
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
<i class="el-icon-zoom-in"/>
</span>
<span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
<i class="el-icon-delete"/>
</span>
</span>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="imageUrl" alt="">
</el-dialog>
</div>
</template>
<script>
import { Component, Vue } from 'vue-property-decorator'
import { uploadImage } from '@/api/common'
import { removeArrEle } from '@/utils'
@Component({
props: {
path: {
type: String,
default() {
return 'common'
}
},
initImage: String
},
watch: {
initImage: function(newValue, oldValue) {
this.doWatchInitImage(newValue)
}
}
})
export default class UploadImagePreview extends Vue {
dialogVisible = false
disabled = false
fileList = []
imageUrl = null
created() {
// this.refresh(this.initImage)
}
refresh(url) {
this.fileList = []
if (url) {
this.fileList.push({ url: url })
}
}
doWatchInitImage(newVal) {
if (!newVal && this.fileList.length > 0) {
this.fileList = []
} else if (newVal && this.fileList.length === 0) {
this.fileList.push({ url: newVal })
} else {
this.refresh(newVal)
}
}
beforeUpload(file) {
return true
}
onUploadSuccess(res, file) {
}
doUpload(params) {
const data = { path: this.path, file: params.file }
uploadImage(data).then(response => {
this.fileList = []
this.fileList.push(params.file)
this.fileList[0].url = response.data
this.$emit('on-image-change', { url: response.data, desc: 'upload done' })
}).catch(err => {
console.log(err.msg)
removeArrEle(this.fileList, params.file)
})
}
handleRemove(file) {
removeArrEle(this.fileList, file)
if (this.fileList.length === 0) {
this.$emit('on-image-change', { url: this.initImage, desc: 'remove all' })
} else {
this.$emit('on-image-change', { url: this.fileList[0].url, desc: 'newest' })
}
}
handlePictureCardPreview(file) {
this.imageUrl = file.url
this.dialogVisible = true
}
mounted() {
this.refresh(this.initImage)
}
}
</script>
<style>
</style>
使用时引入该组件后直接使用
<upload-image-preview path="logo" :init-image="initImageUrl" @on-image-change="onImageChange"/>
onImageChange(data) {
console('新上传图片得到的url =>', data.url)
}
7320

被折叠的 条评论
为什么被折叠?



