Vue js text selection filter

I need help writing a text selection filter using vuejs. The idea is to cross a given array of words, and if there is a match, apply a span with the class to that word. The problem is that I cannot return html formatted data using vuejs. Any ideas would 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 }) 
+8
javascript formatting text
source share
4 answers

As Jeff said, the main mustache interprets the data as plain text.

You can add your range by replacing the query with the String.replace () method.

Here is a basic example: https://jsfiddle.net/0jew7LLz/

 Vue.filter('highlight', function(words, query) { return words.replace(query, '<span class="highlight">' + query + '</span>') }); 
+8
source share

You need to use {{{ foo | highlight }}} {{{ foo | highlight }}} with three brackets, not 2 {{}} . Two curly braces elude HTML.

+4
source share

HTML interpolations {{{foo}}} have been removed in favor of the v-html directive in vuejs2.X , so from version 2.x Vue.js allows you to use JavaScript templates (React Style) in addition to HTML templates.
@Jeff's answer is correct, but for versions of vuejs 1.x, but in case {{{}}} didn’t work for you guys, or if you want to evaluate tags in HTML and from a reliable source, for example, if you want to add <strong></strong> , then you need to use v-html, v-html to ask Vue to evaluate the string as HTML:

 <span v-html="$options.filters.highlight(item, val)">{{ item }}</span> 

highlight filter:

 Vue.filter('highlight', function(word, query){ var check = new RegExp(query, "ig"); return word.toString().replace(check, function(matchedText,a,b){ return ('<strong>' + matchedText + '</strong>'); }); }); 

or you can use the @Thomas Ferro filter

+3
source share

The idea is to use split and keep words that match the regular expression.

Here is a user-friendly safe component that speeds up html and highlights a regular expression that searches for a few words:

 Vue.component('child', { props: ['msg', 'search', 'effect'], template: '<span><span v-for="(s, i) in parsedMsg" v-bind:class="getClass(i%2)">{{s}}</span></span>', methods: { getClass: function(i) { var myClass = {}; myClass[this.effect] = !!i; return myClass; }, }, computed: { parsedSearch : function () { return '(' + this.search.trim().replace(/ +/g, '|') + ')'; }, parsedMsg: function() { return this.msg.split( new RegExp(this.parsedSearch , 'gi')); } } }) new Vue({ el: '#app', } // ... }) 

Usage example:

 <div id="app"> <child msg="My life so good and awesome, is'nt it great?" search=" life is good " effect='highlight'> </child> </div> 

jsfiddle:

https://jsfiddle.net/50xvqatm/

+1
source share

All Articles