封装好的 上传图片组件 以后使用可以直接调用
在commponents 下创建一个Upload.vue文件
<template>
<div class="upload">
<el-upload
ref="uploadInfo"
:action="uploadBaseUrl"
:on-success="uploadSuccess"
:limit="1"
list-type="picture-card"
:headers="myHeaders"
:file-list="alreadyList"
:class="{ hide: alreadyList.length !== 0 }"
>
<i slot="default" class="el-icon-plus"></i>
<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"></i>
</span>
<span class="el-upload-list__item-delete" @click="handleRemove(file)">
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible" :append-to-body="true">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</template>
<script>
export default {
name: "upload",
data() {
return {
loginInfo: JSON.parse(localStorage.getItem("user")),
uploadBaseUrl: "",
dialogVisible: false,
dialogImageUrl: "",
alreadyList: [],
myHeaders:{token:localStorage.getItem("token")}
};
},
props: ["fileUrl", "pic"],
computed: {},
watch: {
fileUrl(newVal) {
if (newVal !== "" && newVal !== null) {
this.alreadyList = [{ name: "", url: newVal }];
} else {
this.handleRemove();
}
if(newVal === undefined) {
this.handleRemove();
}
},
},
methods: {
handleRemove(file) {
this.$refs.uploadInfo.clearFiles();
this.$emit("update:pic", "");
this.alreadyList = [];
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
uploadSuccess(response) {
// console.log(response);
this.$message.success("上传成功");
// localStorage.setItem('avatar',response.data)
this.$emit("update:pic", response.data);
},
},
mounted() {
if (this.fileUrl !== "" && this.fileUrl !== null) {
this.alreadyList = [{ name: "", url: this.fileUrl }];
} else {
this.handleRemove();
}
if(this.fileUrl === undefined) {
this.handleRemove();
}
console.log(this.loginInfo)
//放入上传地址
this.uploadBaseUrl =
' http://123.123.13.12:8081'+
"/user/upAvatar"
},
};
</script>
<style scoped lang="less">
.upload {
.hide {
::v-deep {
.el-upload--picture-card {
display: none;
}
}
}
}
</style>
使用的时候在需要的组件中 引入Upload.vue
components:{
Upload
},
在需要的地方添加
<Upload :fileUrl="userinfo.avatar" :pic.sync="avatar" />
<div >图片大小要求:750*392 像素</div>
:fileUrl 传入图片地址 :pic.sync 传出图片地址
然后就ok啦