【问题标题】:Highlighting search string in returned results在返回的结果中突出显示搜索字符串
【发布时间】:2020-12-04 16:38:59
【问题描述】:

v-modelsearch,它与用户输入搜索字符串的输入字段相关联。

然后,计算方法过滤条目并返回包含搜索字符串的条目。

原始的,没有搜索字符串突出显示,如下所示:

computed: {
      filteredEntries() {
        if (this.search !== null && this.search !== '' && this.search.length > 0) {
          return this.json.filter(entry => {
            return JSON.stringify(entry).toLowerCase().indexOf(this.search.toLowerCase()) > -1
          })
        }
        else {
          return null
        }
      },
(...)

而我试图以错误告终的结果如下:

computed: {
      filteredEntries() {
        if (this.search !== null && this.search !== '' && this.search.length > 0) {
          return this.json.filter(entry => {
            return JSON.stringify(entry.replace(
                                 this.search, 
                                 `<span style="background: #f0adf0;">${this.search}</span>`)
             ).toLowerCase().indexOf(this.search.toLowerCase()) > -1
          })
        }
        else {
          return null
        }
      },
(...)

Vue 抛出的错误是TypeError: entry.replace is not a function

json 变量看起来像(所有值都是可搜索的):

[
    {
        "id": 10,
        "owner": "Debbie",
        "items": "GTX-200, IOI-209, UTF-120"
    },
    {
        "id": 14,
        "owner": "Greg",
        "items": "FVV-300, UPI-229, UDO-175"
    },
    (...)
]

处理后的数据显示在以下结构中:

<v-card v-for="data in filteredEntries" :key="data.id">
  <v-card-title>{{ data.items }}</v-card-title>
</v-card>

甚至可以在这里突出显示搜索字符串,还是应该在其他地方完成?

【问题讨论】:

  • 哪个错误以及您使用什么来呈现突出显示的内容?
  • 我是TypeError: entry.replace is not a function(我刚刚把它放到了帖子里)。
  • json 看起来怎么样?
  • json 已添加到帖子中。不幸的是,转换为字符串的提案不起作用。
  • 如何显示突出显示的内容?

标签: javascript vue.js ecmascript-6


【解决方案1】:

尝试将 json 数组转换为字符串,然后将搜索值替换为突出显示的值:

computed: {
      filteredEntries() {
     return this.json.map(entry=>JSON.stringify(entry)).join('##').replace(this.search, `<span style='background: #f0adf0;'>${this.search}</span>`).split("##").map(entry=>JSON.parse(entry))
     }

}

json = [{
    "id": 10,
    "owner": "Debbie",
    "items": "GTX-200, IOI-209, UTF-120"
  },
  {
    "id": 14,
    "owner": "Greg",
    "items": "FVV-300, UPI-229, UDO-175"
  },
]

let search = "UPI"

let highlighted = json.map(entry => JSON.stringify(entry)).join('##').replace(search, `<span style='background: #f0adf0;'>${search}</span>`).split("##").map(entry => JSON.parse(entry))

console.log(highlighted)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 2017-12-22
    • 2015-08-31
    • 2012-02-16
    • 2014-03-07
    • 2010-09-16
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多