I need help writing a text highlight filter using vuejs. The idea is to loop through a given array of words and if there is a match, apply a span with a class to that word. The problem I have is that, I can't seem to return data with html formatting with vuejs. Any ideas will be highly appreciated. I am really stuck with this.
Vue.filter('highlight', function(words, query){
//loop through **words** and if there is a match in **query**
//apply a <span> with some style
//At the end return formatted string to html page
})
HTML interpolations {{{ foo }}} have been removed in favor of the v-html directive in vuejs2.X, thus from version 2.x, Vue.js allows for raw JavaScript templating (React-style) in addition to HTML templating.
@jeff's answer is correct but for vuejs 1.x versions, but in case {{{}}} didn't work for you guys or if you want to evaluate the tags in the HTML, and from a trusted source, example, if you want to add a
<strong></strong>
tag, then you need to use v-html, the v-html to ask Vue to evaluate the string as HTML:highlight filter:
or you can use @Thomas Ferro's filter
As Jeff just said, the basic mustaches interprets the data as plain text.
You can add your span by replacing the query with the String.replace() method.
Here's a basic example: https://jsfiddle.net/0jew7LLz/
You need to use
{{{ foo | highlight }}}
with 3 braces, not with 2{{}}
. Two braces escapes HTML.The idea is to use split and keep the words that the regex matches.
Here is a user safe component that escapes html and highlights a regexp that searches for multiple words:
Usage example:
jsfiddle:
https://jsfiddle.net/50xvqatm/