Vue.js Search Highlight

Introduction

Vue.js tutorial gives Grid Component Example (Search Component) here. To make users easier find the letters matched, I add a highlight function to it as following:

Vue.js Search Highlight_第1张图片
vuejs-search-highlight

Code

  1. Edit and See outcome in JSFiddle
  2. Github Code Page

Details

It is pretty easy to make search highlight with only 10 lines of codes!

The idea of achieving this is to add a filter to match the search key in the table.

Vue.filter('highlight', function(words, query){
    var iQuery = new RegExp(query, "ig");
    return words.toString().replace(iQuery, function(matchedTxt,a,b){
        return ('' + matchedTxt + '');
    });
});

In the JS code, RegExp function is to make case insensitive. Then the next line of code uses JS original function replace to add a tag with highlight CSS to matched letters.

In the HTML, apply the filter we write to the [content], matching by the [filterKey].

{{{[content] | highlight [filterKey]}}}

The final step: add highlight style in CSS file.

.highlight {
    background-color: yellow;
}

Highlight done with exactly ten lines of codes! Enjoy your achievement :)

(With any question, contact me anytime by leaving a comment here. I will reply ASAP. -- Hubert Wang)

你可能感兴趣的:(Vue.js Search Highlight)