有时候我们的需求和组件提供的不一致,就需要自己封装组件,有的功能实现起来很麻烦,产品要做一个双击图片打开预览的功能,原生js实现有点费劲。我们看一下Image 的源码,发现大图预览是一个小组件image-viewer ,打开看看它的props ,如下
props: {
urlList: {
type: Array,
default: () => []
},
zIndex: {
type: Number,
default: 2000
},
onSwitch: {
type: Function,
default: () => {}
},
onClose: {
type: Function,
default: () => {}
}
}
我们需要使用到的就只有urlList 与onClose 两个属性 ,一个用来放图片链接一个用来关闭查看器。
需要使用的属性我们知道了,然后我们就在代码里面引入image-viewer 就可以直接使用。
<template>
<div class="picture">
<div class="demo-image__lazy">
<div
class="list_item"
ref="list_item"
v-for="(item, index) in urls"
:key="item.id"
@click="isChecked($event, index)"
@dblclick="onPreview(index)"
>
<el-image :src="item.url" lazy fit="contain" class="img_lazy">
<div slot="error" class="image-slot">
加载失败
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
<input
type="checkbox"
class="checkbox_img"
ref="checkbox_img"
:value="item.id"
v-if="img_error"
/>
</div>
<!-- 图片预览 -->
<el-image-viewer
v-if="showViewer"
:on-close="closeViewer"
:url-list="getSrcList(nowIndex)"
/>
</div>
</div>
</template>
<script>
// 导入组件
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import bus from "../assets/js/eventBus.js";
export default {
components: { ElImageViewer },
data() {
return {
count: 10,
loading: false,
urls: [], //图片列表
srcList: [], //存放预览图
time: null,
showViewer: false,
nowIndex: "",
id_arr:[]
};
},
methods:{
// 单击图片选中复选框
isChecked(e, index) {
// 阻止冒泡
window.event ? (window.event.cancelBubble = true) : e.stopPropagation();
// 阻止默认事件
if (e.preventDefault) {
e.preventDefault();
} else {
window.event.returnValue == false;
}
clearTimeout(this.time); //首先清除计时器
this.time = setTimeout(() => {
if (this.$refs.checkbox_img[index].checked) {
this.$refs.checkbox_img[index].checked = false;
this.id_arr.splice(
this.id_arr.indexOf(this.$refs.checkbox_img[index].value),
1
);
} else {
this.$refs.checkbox_img[index].checked = true;
this.id_arr.push(this.$refs.checkbox_img[index].value);
}
}, 300); //大概时间300ms
},
// 图片预览
onPreview(index) {
clearTimeout(this.time); //清除
this.showViewer = true;
this.nowIndex = index;
},
// 以当前点击的预览图为首页
getSrcList(nowIndex) {
return this.srcList
.slice(nowIndex)
.concat(this.srcList.slice(0, nowIndex));
},
// 关闭图片查看器
closeViewer() {
this.showViewer = false;
}
}
}
此段代码还包含了复选框的循环,同一个元素上绑定单击和双击事件(利用定时器解决双击事件不生效问题);
let timer = null;
//单击事件
isChecked(){
clearTimeout(this.time); //首先清除计时器
this.timer = setTimeout(() => {
console.log('单击')
},300)
},
//双击事件
onPreview(index) {
clearTimeout(this.timer); //清除
},
|