[Vuejs]-How to add a html class in a Vue data string?

1πŸ‘

βœ…

To achieve expected result, use below option creating below highlight method

  1. Created highlight method inside loop
  2. Check index of word-HOPE
  3. Use v-html to using that variable


    methods: {
    highlight: function(val) {
    if(val.indexOf('HOPE') !== -1){
    return val.replace("HOPE", 'HOPE');
    }
    return ''+val+''

    }
    }


working code for reference:

var app = new Vue({
  el: '#app',
  data:  function() {
        return {
            locations: [{
                    id: 1,
                    name: 'Example',
                    need: "Lorem ipsum HOPE dolor sit amet.",
                },
                {
                    id: 2,
                    name: 'Example 2',
                    need: "Morbi et lobortis ante, HOPE eu viverra quam.",

                },

              ]
            }
    },
  methods: {
     highlight: function(val) {
       if(val.indexOf('HOPE') !== -1){
        return val.replace("HOPE", '<span class="highlightText">HOPE</span>');       
       }
       return '<span>'+val+'</span>'

  }
  }
})
.highlightText{
  background: red
}
<div>
  <div id="app">
    <div v-for="(location, index) in locations">
            <p class="text-base text-navy-500 leading-tight mt-2">
           
              <div v-html="highlight(location.need)"></div>
            </p>
  </div>
<div>

codepen – https://codepen.io/nagasai/pen/WNegWXx

πŸ‘€Naga Sai A

Leave a comment