Vant 代码实现图片展示及点击放大查看
<template>
<div>
<van-image
v-for="(img, index) in images"
:key="index"
:src="img.url"
:width="img.width"
:height="img.height"
@click="showImage(index)"
/>
<van-image-preview
:images="images"
v-model:show="showPreview"
@change="handleChange"
/>
</div>
</template>
<script>
export default {
data() {
return {
images: [
{ url: 'https://example.com/image1.jpg', width: 200, height: 200 },
{ url: 'https://example.com/image2.jpg', width: 300, height: 300 },
{ url: 'https://example.com/image3.jpg', width: 400, height: 400 }
],
showPreview: false
};
},
methods: {
showImage(index) {
this.showPreview = true;
this.$nextTick(() => {
this.$refs.preview.setCurrentIndex(index);
});
},
handleChange(index) {
console.log('Current image index:', index);
}
}
};
</script>
<p>在上面的示例中,我们使用 <code>van-image</code> 组件展示了三张图片,并给每张图片绑定了点击事件 <code>@click="showImage(index)"</code>。点击图片时会调用 <code>showImage</code> 方法,将 <code>showPreview</code> 属性设置为 <code>true</code>,并使用 <code>this.$refs.preview.setCurrentIndex(index)</code> 方法设置预览组件的当前索引。</p>
<p>同时,在模板中我们还添加了 <code>van-image-preview</code> 组件,用于展示图片预览。我们通过 <code>v-model:show</code> 将预览组件的显示状态绑定到 <code>showPreview</code> 属性上,并监听 <code>@change</code> 事件在图片切换时触发 <code>handleChange</code> 方法。</p>
<p>这样,当用户点击图片时,就会弹出图片预览,并且可以在预览中放大查看每张图片。</p>
原文地址: https://www.cveoy.top/t/topic/o4rf 著作权归作者所有。请勿转载和采集!