TypeError: Cannot read properties of undefined (reading 'filter')

发布时间 2023-04-27 17:31:01作者: yjxQWQ

TypeError: Cannot read properties of undefined (reading 'filter')

  const filterTableData = computed(() =>
      store.data.users!.filter(
        (data) =>
          !search.value ||
          data.nick.toLowerCase().includes(search.value.toLowerCase())
      )
    );at.vue:848 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'filter')

这个错误可能是因为store.data.usersundefined,无法对其调用filter()方法。你可以在使用computed之前检查store.data.users是否为undefined,或者在computed表达式中使用可选链操作符(?.)来防止这种情况发生。例如:

const filterTableData = computed(() =>
  store.data.users?.filter(
    (data) =>
      !search.value ||
      data.nick.toLowerCase().includes(search.value.toLowerCase())
  ) || []
);

这里使用了可选链操作符和一个空数组作为默认值,如果store.data.usersundefined,则返回空数组。