v-html使用img点击实现放大效果
Sonder
2023-07-14
3925字
10分钟
浏览 (1.2k)
/**
* JS获取html代码中所有的图片地址
* @param htmlstr
* @returns arr 数组
*/
export function getimgsrc(htmlstr) {
let reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/g;
let arr = [];
let tem = 0;
//eslint-disable-next-line
while ((tem = reg.exec(htmlstr))) {
arr.push(tem[2]); // eslint-disable-line
}
return arr;
}
<template>
<div class="image-expansion" :class="classArr">
<div @click.stop="hanldeImage($event)" v-html="formatHtmlData"></div>
<el-image-viewer
v-if="imgPreviewUrl"
:initial-index="subscript"
:src="imgPreviewUrl"
:on-close="closeViewer"
:url-list="imgList"
></el-image-viewer>
</div>
</template>
<script>
import { getimgsrc } from '../../utils/getimgsrc';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
export default {
components: {
ElImageViewer
},
props: {
htmlData: {
type: String,
default: () => {
return '';
}
},
classArr: {
type: Array,
default: () => {
return ['min'];
}
},
isArticle: {
type: Boolean,
default: () => {
return false;
}
}
},
data() {
return {
imgList: [],
formatHtmlData: '',
imgPreviewUrl: '',
subscript: 0
};
},
computed: {},
watch: {
//监听数据,防止数据不更新
htmlData: {
handler(newName, oldName) {
//判断是否为文章
if (this.isArticle) {
newName ? (this.formatHtmlData = newName.replace(/(<([^>]+)>)/gi, '').replace(/[\r\n]/g, '')) : '';
} else {
//剔除strong和p标签
newName ? (this.formatHtmlData = newName.replace(/(<\/?strong.*?>)|(<\/?p.*?>)/g, '')) : '';
//获取html全部图片,push成图片数组
this.imgList = Object.values(getimgsrc(this.formatHtmlData));
//获取图片下标
let subscript = this.imgList.indexOf(this.imgPreviewUrl);
this.subscript = subscript > -1 ? subscript : 0;
}
},
immediate: true
}
},
mounted() {},
methods: {
//监听点击事件
hanldeImage(event) {
if (event.target.nodeName === 'IMG' || event.target.nodeName === 'img') {
//获取点击的图片url,decodeURIComponent转码一下,防禁url转码
this.imgPreviewUrl = decodeURIComponent(event.target.currentSrc);
//获取图片下标
let subscript = this.imgList.indexOf(this.imgPreviewUrl);
this.subscript = subscript > -1 ? subscript : 0;
//禁止遮罩层后面的内容滚动
document.documentElement.style.overflowY = 'hidden';
} else {
this.$emit('goDetail');
}
},
//关闭弹框
closeViewer() {
this.imgPreviewUrl = '';
//恢复遮罩层后面的内容滚动
document.documentElement.style.overflowY = 'auto';
}
}
};
</script>
<style lang="scss" scoped>
.image-expansion {
}
.min {
/deep/ img {
cursor: pointer;
height: 28px;
padding: 0 10px 3px;
}
}
.max {
/deep/ img {
cursor: pointer;
}
}
.class1 {
/deep/ div {
font-size: 15px;
font-family: Microsoft YaHei;
font-weight: 400;
color: #888888;
line-height: 30px;
}
}
</style>