如何使用Vue的v-if指令仅显示JSON数组中checked为true的<th>/<tr>
解决方案
核心思路
通过v-if指令结合父组件传入的activeColumns数组,判断对应列的checked值是否为true,以此控制<th>和<td>的显示/隐藏。同时优化组件的类型定义,保证代码规范。
修改后的代码
App.vue(保持原代码即可)
<Overview :activeColumns="items" ></Overview> <script lang="ts" setup> const items = [ { id: 0, text: 'date', checked: true }, { id: 1, text: 'name', checked: false }, { id: 2, text: 'day', checked: false }, { id: 3, text: 'time', checked: false }, { id: 4, text: 'created', checked: false }, { id: 5, text: 'reason', checked: true }, { id: 6, text: 'comment', checked: true }, ]; </script>
Overview.vue(关键修改部分)
<script lang="ts" setup> // 修正props类型,明确数组元素结构 const props = defineProps<{ activeColumns: Array<{ id: number; text: string; checked: boolean; }>; }>(); // 封装辅助函数,统一判断列的可见性 const isColumnVisible = (text: string) => { const column = props.activeColumns.find(item => item.text === text); return column?.checked ?? false; }; </script> <template> <table> <thead> <tr> <th class="date" v-if="isColumnVisible('date')"> <CustomComponent /> </th> <th class="name" v-if="isColumnVisible('name')"> <OtherCustomComponent /> </th> <th class="reason" v-if="isColumnVisible('reason')"> <!-- 对应reason列的内容 --> </th> <th class="comment" v-if="isColumnVisible('comment')"> <!-- 对应comment列的内容 --> </th> </tr> </thead> <tbody> <tr> <td class="date" v-if="isColumnVisible('date')"></td> <td class="name" v-if="isColumnVisible('name')"></td> <td class="reason" v-if="isColumnVisible('reason')"></td> <td class="comment" v-if="isColumnVisible('comment')"></td> </tr> </tbody> </table> </template>
关键说明
- 类型修正:将
activeColumns的props类型从{}改为明确的数组结构,避免类型错误,提升代码可读性。 - 辅助函数:
isColumnVisible函数统一处理列的可见性判断,后续新增列只需调用该函数即可,减少重复代码。 - v-if绑定:直接在
<th>和<td>上绑定v-if="isColumnVisible('列名')",当对应列的checked为true时自动显示元素,否则隐藏。 - 响应式保障:Vue的props本身具备响应式,当父组件的
items数组变化时,子组件会自动同步更新视图。
内容的提问来源于stack exchange,提问作者Some Name
相关产品推荐
相关产品推荐

