Hubert Wang

I am
Hubert Wang

Wechat Official Account
Find fun things here!

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:

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 ('<span class=\'highlight\'>' + matchedTxt + '</span>');
    });
});

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 <span> 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 below. I will reply ASAP. -- Hubert Wang)

1760
TOC
Comments
Write a Comment