<template>
<div class="alert-box-item">
<div class="bigImg-div" v-for="(item,index) in arryImg" :key="index">
<img class="bigImg" :src="item" />
</div>
<div class="bigImg-div" @click="toGetImg">
<img class="bigImg" src="../assets/tj.png" />
</div>
</div>
</template>
<script>
let inputElement = null;
export default {
data() {
return {
arryImg : [],//用来存储图片路径
};
},
methods: {
toGetImg() {
if (inputElement === null) {
// 生成文件上传的控件
inputElement = document.createElement("input");
inputElement.setAttribute("type", "file");
inputElement.style.display = "none";
if (window.addEventListener) {
inputElement.addEventListener("change", this.uploadFile, false);
} else {
inputElement.attachEvent("onchange", this.uploadFile);
}
document.body.appendChild(inputElement);
}
inputElement.click();
},
uploadFile(el) {
if (el && el.target && el.target.files && el.target.files.length > 0) {
console.log(el);
const files = el.target.files[0];
const isLt2M = files.size / 1024 / 1024 < 2;
const size = files.size / 1024 / 1024;
console.log(size);
// 判断上传文件的大小
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
} else if (files.type.indexOf("image") === -1) {
//如果不是图片格式
// this.$dialog.toast({ mes: '请选择图片文件' });
this.$message.error("请选择图片文件");
} else {
const that = this;
const reader = new FileReader(); // 创建读取文件对象
reader.readAsDataURL(el.target.files[0]); // 发起异步请求,读取文件
reader.onload = function () {
// 文件读取完成后
// 读取完成后,将结果赋值给img的src
that.arryImg.push(this.result)//将每次上传的图片放到数组中
// that.valueUrl = this.result;
console.log(that.arryImg);
// 数据传到后台
//const formData = new FormData()
//formData.append('file', files); // 可以传到后台的数据
};
}
}
},
//将选中的图片从数组中删除
remove: function (e) {
// 删除用户不喜欢的图片
this.arryImg.splice(e, 1); //删除数组索引2的位置以后的1个元素
},
},
};
</script>
<style>
.alert-box-item {
overflow: hidden;
}
.alert-box-item::after{
display: block;
content: "";
clear: both;
}
.bigImg-div {
width: 100px;
height: 100px;
/* border-radius: 100%; */
overflow: hidden;
border: 1px solid #ddd;
float: left;
}
.bigImg {
display: block;
width: 100%;
height: 100%;
/* border-radius: 100%; */
}
</style>
vue上传图片并显示
最新推荐文章于 2023-09-08 14:06:46 发布