【问题标题】:[Vue warn]: Error in render: "TypeError: post.text.toLowerCase is not a function"[Vue 警告]:渲染错误:“TypeError:post.text.toLowerCase 不是函数”
【发布时间】:2020-10-04 09:29:45
【问题描述】:

我收到此错误。我正在尝试使用我的搜索栏(输入)过滤我的数组 我正在按照计算进行搜索操作。

<div class="post"
    @click="getData(post.header,post.text)"
    v-for="(post) in searchList"
    v-bind:item="post"
    v-bind:key="post._id"
    >

计算属性

computed:{
  searchList() {
    return this.posts.filter(post => {
      return post.text.toLowerCase().includes(this.lookfor.toLowerCase())
    })
  }
},

请帮帮我,谢谢

This is where i am calling computed function

This is computed property

This is error

【问题讨论】:

  • 似乎至少对于您的posts 之一,post.text 不是字符串。在你的filter回调中添加一些像这样的简单调试怎么样~console.log(typeof post.text, post.text)
  • 你可以简单地返回return post.text &amp;&amp; post.text.toLowerCase().includes(this.lookfor.toLowerCase())
  • @Jhecht 这不太可能奏效。如果post.textnullundefined,则错误消息会有所不同。话虽如此,对于某些记录,post.text 可能是布尔值 false
  • 您需要检查您的 post.text。只有String 的类型有方法.toLowerCase()

标签: vue.js vuejs2


【解决方案1】:

似乎至少对于您的一篇帖子,post.text 不是字符串。

最简单的想法是过滤掉这些非字符串

computed: {
  searchList () {
    const search = this.lookfor.toLowerCase()
    return this.posts.filter(post => typeof post.text === 'string'
      && post.text.toLowerCase().includes(search))
  }
}

或者,您可以使用更新的功能,例如 Optional Chaining

return post.text.toLowerCase().?includes(search)

【讨论】:

  • 你也可以运行post.text &amp;&amp; post.text.toLowerCase &amp;&amp; post.text.toLowerCase().includes(search)
  • @Jhecht 为什么要在两个完成工作时执行三个评估?
  • 我见过一些代码库不喜欢使用 typeof,除非绝对必要(我以前的工作就是其中之一)。还应该注意的是,如果目标浏览器支持它(或者如果你正在使用 babel),你也可以选择链接
  • @Jhecht 你有理由不喜欢它吗? MDN page 上没有适用的警告(旧 Internet Explorer 只有一个)。另外,你的意思是"optional chaining"?如果是这样,那么是的,这是一个选择。我会把它添加到我的答案中
  • 我对此没有任何强烈的感觉。只是把信息放在那里。有些人不喜欢使用 typeof,所以在调用之前检查函数是否存在就可以了。顺便说一句,在您的示例中,它应该是 post.text?.toLowerCase().includes(search),因为我们不确定 text 属性是否具有 toLowerCase 方法。
猜你喜欢
  • 2020-10-12
  • 2021-01-12
  • 1970-01-01
  • 2019-01-03
  • 2018-11-19
  • 2021-02-13
  • 2017-10-20
  • 1970-01-01
  • 2021-03-07
相关资源
最近更新 更多