vue项目中显示图片下载(使用vant的图片预览)
<template><van-image-preview v-model="isShowImg" :images="image" @change="imgChange"><div slot="cover" class="color-high"><van-icon name="down" class="down-img" @cl...
·
<template>
<van-image-preview v-model="isShowImg" :images="image" @change="imgChange">
<div slot="cover" class="color-high">
<van-icon name="down" class="down-img" @click="downLoadHandle"/>
</div>
</van-image-preview>
</template>
//想要让下载图标显示,要改变van-image-preview__cover的属性(自己写,还要修改vant的官网css样式,不然图标没有显示)
.van-image-preview__cover{
bottom:20% !important;
left:44% !important;
}
<script>
import {ImagePreview} from 'vant';//从vant导入图片预览组件
export default{
//传入的参数
props:{
isShow:Boolean,//控制是否显示组件
image:{type:Array,default(){return []}},//要显示的数组,简单数组格式,
},
computed:{
//必须重新在组件中定义一个控制组件显示的值,不然会报错
isShowImg:{
set(val){this.$emit('close'),val},//用于父组件接受,改变isShow的值
get(){return this.isShow}
}
},
data(){
return{
index:0,//图片的下标
}
},
methods:{
downloadHandle(){
let image = new Image();
image.setAttribute('crossOrigin','anonymous');
let _this=this;
image.onload = function(){
let canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext("2d");
context.drawImage(image,0,0,image.width,image.height);
let url = canvas.toDataURL(_this.image(_this.index));
let a =document.createElement('a');
let event = new MouseEvent('click');
a.download = Math.random()*1000+'.jpg'||'photo';
a.href=url;
a.dispatchEvent(event)
}
image.src=_this.image(_this.index);
},
imgChange(index){this.index=index;}
}
}
</script>
5)父组件调用
<template>
<image-preview :isShow="isShow" :image="filex" @close="closeImg"></image-preview>
//此处的filex必须是简单的数组['1','2']
</template>
<script>
import ImagePreview from '组件路径'
</script>
更多推荐
已为社区贡献9条内容
所有评论(0)