You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过按钮触发filter()实现演出内容动态筛选?

基于标签筛选演出内容的实现方案

核心思路

使用filter()是完全合适的方案,而且可以通过存储当前选中的筛选条件来避免重复编写筛选逻辑,和你实现handleActiveIndex的思路一致——不用为每个按钮硬编码筛选规则,只需要把选中的筛选值绑定到状态,再用这个状态统一处理筛选逻辑。

具体实现步骤

1. 新增状态存储筛选条件

在setup里添加响应式状态,记录当前选中的子标签值:

const selectedChoice = ref(labels.value[0].choice[0]); // 默认选中第一个主标签的“全部”

2. 给子标签添加点击事件

修改模板里的子标签部分,添加点击事件来更新选中的筛选值,同时可以加样式标记选中状态:

<!-- 子标签 -->
<div class="choice-list">
  <div
    class="choice"
    :class="{ active: choice === selectedChoice }"
    v-for="(choice, index) in labels[activeIndex].choice"
    :key="index"
    @click="handleSelectChoice(choice)"
  >
    {{ choice }}
  </div>
</div>

3. 实现筛选逻辑(用计算属性自动响应)

用computed属性来生成筛选后的演出列表,这样状态变化时会自动重新计算,不用手动调用filter():

import { ref, computed } from 'vue';

// ... 其他代码 ...

const filteredShows = computed(() => {
  // 如果选中“全部”,直接返回所有演出
  if (selectedChoice.value === '全部') {
    return shows.value;
  }
  // 否则筛选category包含当前选中值的演出
  return shows.value.filter(show => {
    return show.category.includes(selectedChoice.value);
  });
});

4. 补充点击事件方法

在setup里添加处理子标签点击的方法:

const handleSelectChoice = (choice) => {
  selectedChoice.value = choice;
};

5. 更新返回值

把新增的状态和方法、计算属性加入返回对象:

return {
  modules: [Pagination, Navigation],
  activeIndex,
  labels,
  shows,
  selectedChoice,
  filteredShows,
  handleActiveIndex,
  handleSelectChoice,
};

扩展优化(可选)

如果需要结合主标签(比如“舞台演出”“节庆活动”)一起筛选,可以给labels的每个对象添加关联字段,同时给演出数据添加对应的分类字段,然后修改筛选逻辑:

// 修改labels结构
const labels = ref([
  {
    type: "舞台演出",
    key: "stage",
    choice: ["全部", "音乐", "中国戏曲", "舞蹈", "戏剧", "综合艺术", "流行音乐会"],
  },
  {
    type: "节庆活动",
    key: "festival",
    choice: ["全部", "国际综艺合家欢", "新视野艺术节", "中国戏曲节", "香港流行文化节", "其他节庆/系列活动"],
  },
  // ... 其他标签
]);

// 修改筛选逻辑
const filteredShows = computed(() => {
  const currentLabelKey = labels.value[activeIndex.value].key;
  if (selectedChoice.value === '全部') {
    return shows.value.filter(show => show.type === currentLabelKey);
  }
  return shows.value.filter(show => {
    return show.type === currentLabelKey && show.category.includes(selectedChoice.value);
  });
});

最终效果

现在点击不同的子标签,filteredShows会自动更新为符合条件的演出列表,你只需要在页面上渲染filteredShows即可,完全不用为每个按钮单独写筛选代码。

内容的提问来源于stack exchange,提问作者Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 00:22:14