简体   繁体   English

在返回的结果中突出显示搜索字符串

[英]Highlighting search string in returned results

The v-model is search and it's linked with input field where user types in their search string. v-modelsearch ,它与用户在其搜索字符串中键入的输入字段链接。

Then, the computed method filters entries and returns those that contain search string.然后,计算方法过滤条目并返回包含搜索字符串的条目。

The original, without search string highlighting, looks like this:原始的,没有搜索字符串突出显示,如下所示:

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
        }
      },
(...)

And what I tried to do ending up with an error looks like:我试图以错误结束的方式看起来像:

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
        }
      },
(...)

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

json variable looks like (all values are searchable): json变量看起来像(所有值都是可搜索的):

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

Processed data is displayed withing constructs like:处理后的数据使用以下结构显示:

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

Is it even possible to highlight the search string in here, or should it be done elsewhere?甚至可以在这里突出显示搜索字符串,还是应该在其他地方完成?

Try to convert the json array to string then replace the search value by that highlighted one:尝试将 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM