v-model
是search
,它与用户在搜索字符串中键入的输入字段链接。
然后,computed方法过滤条目并返回那些包含搜索字符串的条目。
原始的,没有突出显示搜索字符串,看起来像这样:
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>
是否可以在这里突出显示搜索字符串,或者应该在其他地方进行?
尝试将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)