Bootstrap Vue:如何根据b-tab激活状态切换对应复选框显隐?
Vue.js实现标签页与复选框联动(不使用v-for)
需求说明
当第一个标签页激活时,仅显示第一个复选框,隐藏另外两个;切换到第二个标签页时,仅显示第二个复选框;切换到第三个标签页时,仅显示第三个复选框,且要求不使用v-for循环实现。
实现方案
利用Bootstrap-Vue的b-tabs组件的v-model绑定激活状态,通过这个状态值直接控制每个复选框的显示隐藏,具体代码如下:
完整组件代码
<template> <div> <!-- 绑定标签页激活状态到activeTab --> <b-tabs content-class="mt-3" justified v-model="activeTab"> <b-tab title="First" active><p>I'm the first tab</p></b-tab> <b-tab title="Second"><p>I'm the second tab</p></b-tab> <b-tab title="Third"><p>I'm the third tab</p></b-tab> </b-tabs> <!-- 根据activeTab的值控制复选框显示 --> <input type="checkbox" name="first" v-show="activeTab === 0" /> <input type="checkbox" name="second" v-show="activeTab === 1" /> <input type="checkbox" name="third" v-show="activeTab === 2" /> </div> </template> <script> export default { data() { return { // 初始激活第一个标签页,索引从0开始 activeTab: 0 } } } </script>
关键细节说明
- 标签页状态绑定:通过
v-model="activeTab"将b-tabs的激活状态与组件的activeTab数据属性绑定,切换标签页时activeTab会自动更新为当前激活标签的索引(第一个标签索引为0,第二个为1,以此类推)。 - 复选框显示控制:用
v-show指令判断activeTab的值,仅当值与复选框对应的标签索引匹配时,才显示该复选框。如果更倾向于通过DOM添加/移除来控制,可以把v-show换成v-if,效果一致。
语义化优化方案(可选)
如果觉得用索引不够直观,可以给每个b-tab设置唯一id,通过id值来判断激活状态,代码如下:
<template> <div> <b-tabs content-class="mt-3" justified v-model="activeTab"> <b-tab id="tab-first" title="First" active><p>I'm the first tab</p></b-tab> <b-tab id="tab-second" title="Second"><p>I'm the second tab</p></b-tab> <b-tab id="tab-third" title="Third"><p>I'm the third tab</p></b-tab> </b-tabs> <input type="checkbox" name="first" v-show="activeTab === 'tab-first'" /> <input type="checkbox" name="second" v-show="activeTab === 'tab-second'" /> <input type="checkbox" name="third" v-show="activeTab === 'tab-third'" /> </div> </template> <script> export default { data() { return { activeTab: 'tab-first' } } } </script>
内容的提问来源于stack exchange,提问作者alisher sherov
相关产品推荐
相关产品推荐

