点击首行按钮时如何更新activeIndex以获取对应对象的选项数组?
问题:点击标签按钮时无法切换activeIndex更新子选项列表
我正在开发一款筛选器及标签组件,点击首行按钮会展开更多搜索选项。目前能显示活跃按钮的子选项,但始终只能获取首个按钮“Stage Performance”的选项,需要更新activeIndex来匹配点击的按钮,请问怎么在点击首行按钮时修改activeIndex?
设计预览

模板代码
<swiper :slidesPerView="5" :navigation="true" :modules="modules" class="mySwiper" > <!-- 遍历标签 --> <swiper-slide v-for="(label, index) in labels" :key="index" @click="handleActiveIndex(index)" > <button class="button-text">{{ label.type }}</button> </swiper-slide> </swiper> <!-- 子选项列表 --> <div class="choice-list"> <div class="choice" v-for="(choice, index) in labels[activeIndex].choice" :key="index" > {{ choice }} </div> </div>
脚本代码
setup() { /* 筛选标签数据 */ const activeIndex = ref(0); const labels = ref([ { type: "Stage Pefromnace", choices: [ "All", "Music", "Chinese Opera", "Dance", "Theatre", "Multi-Arts", "Pop Concerts", ], }, { type: "Festivals", choices: [ "All", "International Arts Carnival", "New Vision Arts Festival", "New Vision Arts Festival", "Chinese Opera Festival", "Hong Kong Pop Culture Festival", "Other Festivals / Series Events", ], }, // 其他数据对象... // ]); return { modules: [Pagination, Navigation], activeIndex, labels, }; }
解决方案
- 添加点击事件处理函数
你已经在模板里绑定了handleActiveIndex(index),但脚本中未定义该方法,直接在setup函数内新增:
const handleActiveIndex = (index) => { activeIndex.value = index; }
修正子选项循环的键名错误
模板中labels[activeIndex].choice存在拼写错误,需与labels数组内的键名保持一致,改为labels[activeIndex].choices将方法暴露给模板
把handleActiveIndex添加到return对象中,确保模板能访问到该方法:
return { modules: [Pagination, Navigation], activeIndex, labels, handleActiveIndex // 新增该行 };
完成以上修改后,点击不同标签按钮时,activeIndex会同步更新,子选项列表也会切换为对应按钮的内容。
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

