1.在文件下新建一个components/UploadImg组件
<template>
<el-upload :action="UploadImgUrl" :disabled="disabled" :headers="headerstoken" :on-success="successfile"
:show-file-list="false" accept="image/png,image/gif,image/jpg,image/jpeg">
<div v-if="imageUrl">
<b @click="removeimg" class="el-icon-delete deleico"></b>
<img width="150" height="100" :src="imageUrl" class="avatar">
</div>
<div v-else @click="Undisabled">
<i class="el-icon-plus avatar-uploader-icon"></i>
</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
UploadImgUrl: 'https://mp.csdn.net/mdeditor/103048073',//上传地址
imageUrl: '',//图片路径
disabled: false,//是否禁用
headerstoken: {}//header验证
}
},
methods: {
successfile(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.disabled = true//一旦选择文件后在没删除的情况下让上传保持禁止状态
this.$emit('getFormImg', res.message[0])//给父组件传入获取到的路径
},
removeimg() {
this.imageUrl = ''
this.$emit('getFormImg', '')//删除时通知父组件值设置为空
},
Undisabled() {
this.disabled = false//解除上传禁止
}
},
mounted() {
if (userinfo) {
this.headerstoken = {'Authorization':userinfo.userToken}
}
}
}
</script>
2.在需要的页面使用该组件
<template>
<el-form :model="formValue" >
<el-form-item prop="userhandCardimg">
<upload-img @getFormImg="successfile($event,'imagename')"></upload-img>
</el-form-item>
</el-form>
</template>
<script>
import UploadImg from '@/components/UploadImg'
export default{
data(){
return{
formValue:{
imagename:''
}
}
},
components: {
UploadImg
},
methods: {
//data父组件传过来的值,
//name当前操作的上传文件的名称用于给后端传值
successfile: function(data, name) {
this.formValue[name] = data
},
}
}
</script>