Reputation: 1868
I have a component in Vue and I have some hard coded data. I need to add the class font-bold uppercase
to a word in the string.
How would I achieve this in Vue?
In the below code, inside data > need
you will see the word HOPE
. I need this word to have the class.
export default {
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.",
},
]
}
}
}
HTML:
<template>
<div>
<div v-for="(location, index) in locations">
<p class="text-base text-navy-500 leading-tight mt-2">
{{ location.need }}
</p>
...
I tried using a method similar to this, but couldn't figure it out: I'm assumming I need a way to search and replace the word in the string...
methods: {
highlight() {
if(!this.query) {
return this.content;
}
return this.content.replace(new RegExp(this.query, "HOPE"), match => {
return '<span class="highlightText">' + match + '</span>';
});
}
Any help would be appreciated.
Upvotes: 0
Views: 526
Reputation: 10975
To achieve expected result, use below option creating below highlight method
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
Upvotes: 1