程序员让前端飞代码改变世界

Vue.js Search Highlight

2016-09-19  本文已影响195人  HongyangWang

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)

上一篇 下一篇

猜你喜欢

热点阅读