给一个字符中的img标签添加图片预览功能,Vant组件、ref和querySelector两种方式实现

Vant安装过程点击进入查看

app.vue中的代码如下:

<template>
  <div ref="box" class="box" v-html="imageText">div>
template>
<script setup>
import { showImagePreview } from 'vant';
import {onMounted, ref} from "vue";
// 给一段文本字符串的html
const imageText = ref(`
`
) // 方式一 querySelector方式 onMounted(()=>{ const box = document.querySelector('.box'); console.log('box', box) // const image_list = box.value.querySelectorAll('img') const image_list = box.querySelectorAll('img') const images = [] image_list.forEach((item,index)=>{ images.push(item.src) item.onclick = ()=>{ showImagePreview({ images, startPosition: index }) } }) }) // 方式二 ref方式 // const box = ref(null) // onMounted(()=>{ // const image_list = box.value.querySelectorAll('img') // const images = [] // image_list.forEach((item,index)=>{ // images.push(item.src) // item.onclick = ()=>{ // showImagePreview({ // images, // startPosition: index // }) // } // }) // })
script> <style scoped lang="less"> style>

效果如下:

未点击时:

给一个字符中的img标签添加图片预览功能,Vant组件、ref和querySelector两种方式实现_第1张图片

点击完后

给一个字符中的img标签添加图片预览功能,Vant组件、ref和querySelector两种方式实现_第2张图片

你可能感兴趣的:(vue,前端,css,javascript,前端,vue.js)