Vue.js Search Highlight

作者: HongyangWang | 来源:发表于2016-09-19 15:36 被阅读195次

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:

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 ('<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 here. I will reply ASAP. -- Hubert Wang)

相关文章

网友评论

    本文标题:Vue.js Search Highlight

    本文链接:https://www.haomeiwen.com/subject/ytlnettx.html