您的位置:首页 > Web前端 > Vue.js

在vue 中使用input type=file 获取上传图片,并转为base64码放在img 的src中,实现预览效果

2020-06-29 04:39 417 查看
<!--页面部分-->
<template>
<div class="hello">
<p class="title">{{ action }}</p>
<p class="selectfile">请选择预览图片</p>
<input class="select" ref="imgInput" type="file" accept="image/*" @change="uploadImg($event)">

<ul v-show="isUpload">
<p class="green" v-if="imgUrl.length!==0">图片预览</p>
<li v-for="(list,index) in imgUrl" :key="list">
<img ref="imgimg" :src="list.url" alt="">
<button class="remove" @click="remove(index)">删除</button>
</li>
</ul>
</div>
</template>
<!--js部分-->
<script>
export default {
name: 'Home',
data () {
return {
action: 'Welcome to my album !',
isUpload:false,
imgUrl:[],
}
},
methods: {
uploadImg(e){
console.log(e.target.files);
this.isUpload=true;
let file=e.target.files[0];
let url='';
var reader = new FileReader();
reader.readAsDataURL(file);
let that=this;
reader.onload = function (e) {
url=this.result.substring(this.result.indexOf(',')+1);
// that.imgUrl='data:image/png;base64,'+url
// that.$refs['imgimg'].setAttribute('src','data:image/png;base64,'+url);
that.imgUrl.push({
id:that.imgUrl.length+1,
url:'data:image/png;base64,'+url
})
}
},
remove(index){
this.imgUrl.splice(index,1)
}
},
}
</script>
<!--样式部分-->
<style scoped>
.green{
color: #42b983
}
ul {
list-style-type: none;
padding: 0;
}
img{
width: 400px;
}
.title{
font-size: 40px;
background: linear-gradient(to right, red, blue);
-webkit-background-clip: text;
color: transparent;
font-weight: 800
}
.remove{
position: relative;
bottom: 120px;
left: 70px;
border-radius: 4px;
background-color: darkred;
border: 1px solid gray;
color: white;
width: 50px;
height: 25px;
text-align: center
}
.select{
opacity:0;
z-index: 111;
position: relative;
top: -50px;
left: 0%;
height: 50px;
width: 163px;
}
.selectfile{
color: white;
padding: 10px 20px;
width: 120px;
background-color: #4180d6;
z-index: 1;
margin: 0 auto;
border-radius: 4px;
}
</style>

效果展示图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: