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

Vue3 Composition API使用computed过滤数组功能失效问题咨询

问题所在

  • 你错误将computed属性同时用作事件回调和过滤后列表:Vue的computed默认是不带参数的getter函数,不能直接作为事件处理函数接收标签云emit出来的tag参数
  • 没有存储当前选中标签的响应式变量:过滤逻辑依赖的选中标签没有持久化存储,导致computed无法正确响应标签选择变化
  • 模板绑定逻辑错误:@tag="filterTils"相当于把emit的tag参数传给了computed,不符合computed的使用规则

修改方案

只需要修改主视图的代码即可,其余两个组件无需改动:

1. 修改script逻辑

<script>
import PostList from "../components/PostList.vue";
import TagCloud from "../components/TagCloud.vue";
import { ref, computed } from "vue";

export default {
  name: "Til",
  components: { PostList, TagCloud },
  setup() {
    const tils = ref([
      {
        id: 1, // 建议新增唯一id作为v-for的key,避免渲染警告
        title: "Symbol#to_proc conversion",
        description: "map(&:to_i) is exactly the same as map { |x| x.to_i }",
        tags: ["ruby"],
      },
      {
        id: 2,
        title: "Symbol#to_proc conversion",
        description:
          "Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum ",
        tags: ["lorem"],
      },
      {
        id: 3,
        title: "Symbol#to_proc conversion",
        description: "map(&:to_i) is exactly the same as map { |x| x.to_i }",
        tags: ["ruby"],
      },
    ]);
    // 新增响应式变量存储当前选中的标签
    const selectedTag = ref('')
    // 新增标签选择事件处理方法
    const onTagSelect = (tag) => {
      // 可选逻辑:重复点击同一个标签就取消选中,显示全部文章
      selectedTag.value = selectedTag.value === tag ? '' : tag
    }
    // 修改computed逻辑,依赖selectedTag自动更新过滤结果
    const filterTils = computed(() => {
      // 未选中标签时返回全部文章
      if (!selectedTag.value) return tils.value
      return tils.value.filter((til) => til.tags.includes(selectedTag.value));
    });
    
    return { tils, filterTils, onTagSelect };
  }
};
</script>

2. 修改模板绑定

<template>
  <div class="home">
    <h1>Today I learned (TIL)</h1>
    <div class="layout">
      <!-- 事件绑定改为新增的处理方法 -->
      <TagCloud :tils="tils" @tag="onTagSelect" />
      <PostList :tils="filterTils" />
    </div>
  </div>
</template>

可选优化

PostList组件中v-for的key不要直接用til对象,建议用新增的唯一id:

<div v-for="til in tils" :key="til.id">

内容的提问来源于stack exchange,提问作者Francois Dumas Lattaque

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:09:03