Preview the image rendered by v-html in vue

Background: For the content rendered by v-html, the pictures in it cannot be directly manipulated, but in some cases it is necessary to zoom in and preview the pictures.

Solution: add the click (getImg) method to the parent element of the rendered content, and the path of the image can be obtained when the image is clicked; then preview through the preview plug-in;

1. Get the image path:

HTML part:

<div @click="getImg($event)">  //在父元素上加上click方法
    <div v-html="currentItem.content"></div> //用v-html渲染内容         
</div>

JS part:

//此处用的vue3

<script setup>
const getImg = ($event) => {
    console.log($event.target.currentSrc)    //当前点击的图片的路径    
}
</script>

2. Image preview, here is the el-image-viewer component in vue:

HTML part:

//hide-on-click-modal 禁止点击空白区域来关闭弹窗
//@close="()=>{showViewer = false}" 预览弹窗关闭时的回调事件
//:url-list="previewList" 预览图片的路径,previewList为数组

<div class="demo-image__preview">
     <el-image-viewer hide-on-click-modal @close="()=>{showViewer = false}" v-if="showViewer" :url-list="previewList" />
</div>

JS part:

<script setup>
import {ref} from 'vue'

const showViewer = ref(false);
const previewList = ref([]);
const getImg = ($event) => {
    previewList.value = [$event.target.currentSrc];
    showViewer.value = true;
}
</script>

3. Complete code:

<template>
  <div class="container">
      <div class="demo-image__preview">
          <el-image-viewer hide-on-click-modal @close="()=>{showViewer = false}" v-if="showViewer" :url-list="previewList" />
      </div>
      <div @click="getImg($event)">         
          <div class="detailContent" v-html="currentItem.content"></div>         
      </div>    
  </div>
</template>


<script setup>
import {ref} from 'vue'

const showViewer = ref(false);
const previewList = ref([]);
const getImg = ($event) => {
    previewList.value = [$event.target.currentSrc];
    showViewer.value = true;
}

</script>

Guess you like

Origin blog.csdn.net/weixin_57092157/article/details/130690527