vue achieve keyword based search highlighting

There is a demand in the existing list of search keywords, and show the data item containing the relevant keywords in the list of keywords and highlighted, so that the needs to be addressed on two issues:

1. Search Keyword Filtering list data

2. Each list highlights key

ps: an array of objects based on this problem, other types of data may refer to this idea.

Search Keywords: filter data is very simple, nothing more than listen search, you can filter the source data, paste the code below:

 1 const search = this.search
 2 if (search) {
 3     this.showdata = this.copyshowdata.filter(data => {
 4          return Object.keys(data).some(key => {
 5              return String(data[key]).indexOf(search) > -1
 6         })
 7     })       
 8 } else {
 9     this.showdata = this.copyshowdata
10 }        

showdata is displayed in the page, copyshowdata is showdata copy, use the restore list, it does nothing.

The above search is to use watch monitor value change process may be calculated using the computed showdata property.


Highlight Keywords: showData idea is traversed, the values for each item is a regular matching (also matches the specified items), using <span class = "highlights-text "> </ span> replace search

. 1  Highlights () {
 2          const = Search the this .search
 . 3          the this .showdata = the this .showdata.map (Item => {
 . 4            for (the let Key in Item) {
 . 5              IF (Key === 'Issuecontent' ) {
 . 6                the let = replaceReg new new the RegExp (Search, 'G') // match the regular key 
. 7                the let ReplaceString = '<span class = "text-Highlights">' + Search + '</ span>' // highlight alternative v-html value 
. 8                Item [Key + '-highlights'] = Item [Key] .replace (replaceReg,replaceString) // start replacement 
. 9              }
 10            }
 . 11            return Item
 12 is          })
 13 is        }

Using v-html = "item [key-highlights]" Render page

Styles also need to be treated separately after rendering, the parent can not be added to the above, and scope to be removed, otherwise the style will not take effect.

1 <style lang="scss">
2   .highlights-text {
3     color: #ff5134;
4   }
5 </style>

Posted a rendering:

 

Guess you like

Origin www.cnblogs.com/licurry/p/11589985.html