F.M.F.
F.M.F.

Reputation: 2292

Vue.js 2: Highlight string occurrence

Is there a convenient way to highlight all string occurrences of a string in a text or an element?

Something like the filter method from vue.js 1?

Upvotes: 0

Views: 1365

Answers (2)

Duy Anh
Duy Anh

Reputation: 770

There are filters in vuejs2 as well. You just create your own method to highlight.

<div>{{ 'some-text' | highlight }}    

new Vue({
  // ...
  filters: {
    highlight: function (value) {
      // logic
    }
  }
})

Upvotes: 1

Kodiak
Kodiak

Reputation: 542

The only problem with my solution is, that the whole v-html-text is now lowercase.. I defined the highlight-method in the methods-block:

methods: {
    highlight(words, query) {
        if(query === '') { return words }
        if(typeof(words) === 'number') {
            words = '' + words + ''
        }
        // when removing the .toLowerCase() your search becomes case-sensitive
        return words.toLowerCase().replace(query, '<span style="background: yellow;">' + query + '</span>')
    }
}

In my template it looks like this:

<span v-html="highlight('This is some sort of test', 'some')"> // should now highlight 'some'

Upvotes: 2

Related Questions