Vue.js嵌套v-for循环中如何仅在点击项对应位置展示子div
核心问题定位
你当前实现的核心缺陷是将所有外层循环渲染出的详情区块,绑定到了同一个全局布尔状态Showmodal上——这个状态没有和具体某一组订单做关联,只要它被设为true,所有外层循环生成的详情div都会同步显示,自然达不到单组控制的效果。
可落地的修改方案
方案1:用「当前激活分组下标」替代全局布尔状态
这是最简洁、不需要修改原始数据结构的实现方式:
- 移除全局变量
Showmodal,新增一个状态activeGroupIndex,初始值设为null(代表所有分组都不展开),用来记录当前要显示详情的是第几组订单 - 按钮点击时,把当前外层循环的
index作为参数传入方法,打开时把activeGroupIndex设为当前传入的下标,关闭时把值重置为null - 每个详情块的
v-show判断逻辑,替换为「当前循环的index 等于 存储的激活下标」时才显示
对应修改后的代码参考:
<template> <div id="app"> <h1>my Orders</h1> <div v-for="(orders, index) in SubmittedOrders" :key="index"> <h3>#2222</h3> <h4>170$</h4> <button @click="openModal(index)">order details</button> <hr> <br> <div v-show="activeGroupIndex === index"> <div v-for="order in orders" :key="order.id"> <h3>{{ order.orderName }}</h3> <h3>{{ order.price * order.quantity }}</h3> </div> <hr> <h3>#2222</h3> <h4>170$</h4> <button @click="closeModal">close Modal</button> </div> </div> </template> <script> export default { data() { return { SubmittedOrders: [ [ { orderName: 'Nissan', price: 50, quantity: 1 }, { orderName: 'ferrari', price: 120, quantity: 2 }, ], [ { orderName: 'porch', price: 90, quantity: 1 }, { orderName: 'Mercedez', price: 180, quantity: 4 }, ], ], activeGroupIndex: null }; }, methods: { openModal(currentIndex) { this.activeGroupIndex = currentIndex; }, closeModal() { this.activeGroupIndex = null; } } } </script>
方案2:为每一组订单挂载独立的显示标记
如果不想依赖全局下标判断,也可以给每一组外层订单对象增加独立的响应式显示属性:
- 在渲染前,为每一组订单数据添加
isShow属性,初始值为false - 打开按钮点击时,直接把当前对应组的
isShow设为true,关闭时设为false - 详情块的
v-show直接绑定当前组的orders.isShow即可
注意:如果是Vue2环境下直接给原始数组项新增属性,需要用
this.$set保证新增属性的响应式,否则修改值不会触发视图更新。
内容的提问来源于stack exchange,提问作者giuliano hell
相关产品推荐
相关产品推荐

