vue中对v-html渲染出来的图片进行预览操作

背景:对于v-html渲染的内容,无法直接对其中的图片进行操作,但某些情况下又需要对图片进行放大预览。

解决办法:在渲染内容的父元素上加上click(getImg)方法,点击图片时可获取到图片的路径;再通过预览插件进行预览;

1.获取图片路径:

HTML部分:

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

JS部分:

//此处用的vue3

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

2.图片预览,此处用的是vue中的el-image-viewer组件:

HTML部分:

//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部分:

<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.完整代码:

<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>

猜你喜欢

转载自blog.csdn.net/weixin_57092157/article/details/130690527