Problem description
Requirements: when we search for a keyword, the back end returns us a string containing the keyword we search. We need to add the highlight effect to the keyword part of the string (similar to the highlight effect of Baidu search keyword). Let’s take a look at the similar effect picture first:
As shown in the figure above, the requirement is very simple, that is, keyword highlighting.
Train of thought analysis
There are two solutions. The first is to cut the string, cut out the keyword and add a color. In this way, the article on string sorting in the previous article has already said that it will not be repeated. Click the link to jump to see the details.
Attach address:https://segmentfault.com/a/11…
Next, let’s talk about the second method, which uses the v-html instruction plus the string replacement method. Without much talking, let’s talk about the code.
<template>
<div id="app">
<div>
<span v-html="highLight(title)">{{title}}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
Title: "five hundred years ago, the monkey king caused havoc in heaven",
Searchword: "Monkey King"
};
},
methods: {
highLight(title){
//If the title contains keywords, replace them
if(title.includes(this.searchWord)){
title = title.replace(
this.searchWord,
//Here is the data in HTML format. It's better to add a style weight to make it safer
'<font style="color:red!important;">'+ this.searchWord +'</font>'
)
return title
}
//Use this if not included
else{
return title
}
}
},
};
</script>
Code rendering:
DOM element review
summary
It seems that v-html doesn’t usually use this Vue instruction, but in fact, in some scenarios, using v-html can solve the problem well
In the demo, the font label is used for demonstration. In fact, it is not necessary to use the font label, but the span label can also be used. Add: Baidu uses the EM tag, and the strong tag must be applied