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

Vue3中如何通过计算属性过滤数组类型Props?

问题解决:props.accounts.filter is not a function

报错的核心原因是props.accounts并非始终是数组类型——可能父组件初始传递的是undefined/null,或者传递过程中类型不符合预期,导致调用数组方法filter时出错。

修复步骤:

1. 给Props添加类型校验与默认值

先确保accounts始终是数组,避免初始值非数组的情况:

<script setup>
import Account from "./Account.vue";
import { ref, computed } from "vue";

// 用对象形式定义Props,指定类型和默认空数组
const props = defineProps({
  accounts: {
    type: Array,
    default: () => [] // 默认返回空数组,避免undefined/null
  }
});

const filteredAccounts = computed(() => {
  return props.accounts.filter((item) => parseFloat(item.Cash) !== 0);
});
</script>

<template>
  <div>
    <div class="d-flex flex-wrap">
      <div class="p-2" v-for="item in filteredAccounts">
        <Account class="" :account="item" />
      </div>
    </div>
  </div>
</template>

2. 额外保险:计算属性里先做类型判断(可选)

如果担心父组件可能传递非数组值,可在计算属性里先校验类型:

const filteredAccounts = computed(() => {
  // 先判断是否为数组,不是的话直接返回空数组
  if (!Array.isArray(props.accounts)) return [];
  return props.accounts.filter((item) => parseFloat(item.Cash) !== 0);
});

为什么直接遍历props.accounts没问题?

Vue的v-for在遍历undefined/null时会自动忽略,不会报错,但调用数组方法filter时就会直接抛出错误——这就是两种场景表现不同的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:04:56