有几个图像。我想让当我点击图片1时弹出图片1,当我点击图片2时我想让图片2弹出。我可以使用类中的索引解决它吗?
Carousel.vue
<template>
<div v-for="(item, index) in items" :key="index">
<img :src="item.thumbnail" />
<button type="button" @click="imgClick()" :class="`img-index--${index}`">button-{{ index }}</button>
</div>
<Modal v-if="showModal" @close="showModal = false">
<div slot="body" v-for="(item, index) in items" :key="index">
<img :src="item.thumbnail" :class="`img-index--${index}`"/>
</div>
</Modal>
</template>
<script>
import Modal from './Modal.vue'
export default {
props: {
items: { type: Array, default: () => [] }
},
data() {
return {
showModal: false
}
},
methods: {
imgClick() {
this.showModal = !this.showModal;
}
},
components: {
Modal: Modal
}
}
</script>
您可以从您的数据中构建新的数据items
prop 并注入一个新属性show: false
对于每个图像。
你不需要2v-for
这样循环。你可以把Modal
第一个循环内的组件,只需使用item.show
显示或不显示模态。
<template>
<div>
<div v-for="(item, index) in photos" :key="index">
<div @click="imgClick(item)" style="cursor:pointer;>
<img :src="item.thumbnail" />
</div>
<Modal v-if='item.show' @close="item.show = false">
<div slot='body'>
<img :src="item.thumbnail" :class="`img-index--${index}`"/>
</div>
</Modal>
</div>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
props: {
items: { type: Array, default: () => [] }
},
data() {
return {
photos: {}
}
},
created() {
this.photos = this.items.map(item => {
return { ...item, show: false }
})
},
methods: {
imgClick(item) {
item.show = true
}
},
components: {
Modal: Modal
}
}
</script>
小提琴示例here https://jsfiddle.net/StpFlp_DDK/nfj5ag7x
注意:您可以将缩略图包裹在 div 内来管理点击图像。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)