Vue.js Search Highlight
Add hightlight to Vue.js Search Component. Detailed intro: http://mr-why.com/post/category/frontend/vuejs-search-highlight, coding based on yyx990803's code of Grid Component Example: https://vuejs.org/examples/grid-component.html
HTML
<script src="https://unpkg.com/vue@2.4.1/dist/vue.js"></script>
<!-- component template -->
<script id="grid-template">
<ul>
<li v-for="suggest in suggestions">{{{ suggest.message | highlight filterKey }}}</li>
</ul>
</script>
<!-- demo root element -->
<div id="demo">
<form>
Search <input v-model="searchParams.key">
</form>
<demo-grid :filter-key="searchParams.key"></demo-grid>
</div>
CSS
body {
font-family: Helvetica Neue, Arial, sans-serif;
font-size: 14px;
color: #444;
}
#search {
margin-bottom: 10px;
}
.highlight {
background-color: yellow;
}
JavaScript
// register the grid component
Vue.component('demo-grid', {
template: '#grid-template',
props: {
filterKey: String
},
data: function () {
return {
searchParams: [
{ key: '' }
],
suggestions: [
{ message: 'Foo' },
{ message: 'Bar' },
{ message: 'Foobar' },
{ message: 'pikachu' },
{ message: 'raichu' }
]
}
},
filters: {
highlight: function(words, query){
var iQuery = new RegExp(query, "ig");
return words.replace(iQuery, function(matchedTxt,a,b){
return ('<span class=\'highlight\'>' + matchedTxt + '</span>');
});
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo'
})