在使用Vue.js为数组中的每个卡片创建一个模态框(Modal)时,我们需要理解几个基础概念:
v-if
或v-show
指令来控制DOM元素的显示与隐藏。v-for
指令来遍历数组并渲染列表。以下是一个简单的Vue 3示例,展示了如何为数组中的每个卡片创建一个模态框:
<template>
<div>
<!-- 卡片列表 -->
<div v-for="(card, index) in cards" :key="index">
<div class="card">
<h3>{{ card.title }}</h3>
<button @click="showModal(index)">查看详情</button>
</div>
<!-- 模态框 -->
<div v-if="activeIndex === index" class="modal">
<div class="modal-content">
<span class="close" @click="showModal(null)">×</span>
<h2>{{ card.title }}</h2>
<p>{{ card.description }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cards: [
{ title: 'Card 1', description: 'This is the first card.' },
{ title: 'Card 2', description: 'This is the second card.' },
// 更多卡片...
],
activeIndex: null, // 当前激活的模态框索引
};
},
methods: {
showModal(index) {
this.activeIndex = index;
}
}
};
</script>
<style>
/* 样式省略 */
.modal {
/* 模态框样式 */
}
.modal-content {
/* 内容样式 */
}
.close {
/* 关闭按钮样式 */
}
</style>
问题:模态框打开后,点击其他地方无法关闭。
解决方法:可以通过监听全局点击事件来关闭模态框,或者在模态框外部添加一个遮罩层,点击遮罩层时关闭模态框。
<template>
<!-- ... -->
<div v-if="activeIndex !== null" class="modal-overlay" @click="showModal(null)">
<!-- 模态框内容 -->
</div>
</template>
<style>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
</style>
确保在实际应用中根据具体需求调整样式和逻辑。
领取专属 10元无门槛券
手把手带您无忧上云