有没有一种方便的方法来突出显示文本或元素中字符串的所有字符串出现?
像vue.js 1中的过滤方法?
在vuejs2中也有filters。您只需创建自己的方法来突出显示。
<div>{{ 'some-text' | highlight }}
new Vue({
// ...
filters: {
highlight: function (value) {
// logic
}
}
})
我的解决方案唯一的问题是,整个v-html文本现在是小写的..我在方法块中定义了highlight-method:
methods: {
highlight(words, query) {
if(query === '') { return words }
if(typeof(words) === 'number') {
words = '' + words + ''
}
// when removing the .toLowerCase() your search becomes case-sensitive
return words.toLowerCase().replace(query, '<span style="background: yellow;">' + query + '</span>')
}
}
在我的模板中,它看起来像这样:
<span v-html="highlight('This is some sort of test', 'some')"> // should now highlight 'some'