功能需求
在某个功能中,使用了 v-html 渲染富文本保存的内容,但是 img 图片也需要可点击来进行预览。
实现
这个时候需要借助 element-plus 组件库中的 el-image-viewer 组件来实现,这个组件在官方文档中并没有写出来,查看源码可知该组件正是 el-image 组件里预览图片所使用的。
HTML 中:
// 在元素上添加click方法
<div v-html="item.content" class="html-content" @click="onPreview($event)"></div>
// 图片预览,使用 el-image-viewer 组件,如已全局引入 element-plus 可直接使用
<el-image-viewer @close="viewClose" v-if="showView" :url-list="previewList" />
JS 中:
const previewList = ref([]) // 预览图片url列表
const showView = ref(false)
const onPreview = (event) => {
const currentSrc = event?.target?.currentSrc;
if (event.target.tagName == 'IMG' && currentSrc) {
previewList.value = [currentSrc]
showView.value = true
}
}
// 关闭预览
const viewClose = () => {
showView.value = false
}
CSS 中:
.html-content {
:deep(img) {
cursor: pointer;
}
}
结论
通过使用 el-image-viewer 组件可完美实现此功能,在不同的需求中也可灵活使用此组件来实现图片预览。