我有一个带有v-html的标签,它会呈现一个html文本并显示出来,如下所示:
<div v-html="htmlText"></div>
Vue.filter('highlight', function (word, query) {
if (query !== '') {
let check = new RegExp(query, "ig");
return word.toString().replace(check, function (matchedText, a, b) {
return ('<strong class="mark">' + matchedText + '</strong>');
});
} else {
return word;
}
<div v-html="$options.filters.highlight(htmlText, myWord)">
</div>
我想突出显示本文中的单词,而不突出显示html标签。 请帮忙。 感谢。
答案 0 :(得分:0)
如果您不反对外部依赖,可以使用mark.js。
它允许使用RegExp突出显示文本,并且可以跨HTML标记工作。以下是与Vue一起使用的示例:
var demo = new Vue({
el: '#demo',
data: {
// The html to highlight
html: '<div>Hello <span>this </span>is <span>some </span>text</div>',
// The html with highlighting
highlightedHtml: '',
// The search term to highlight
search: 'Hello'
},
watch: {
// When the search term changes: recalculate the highlighted html
'search': {
handler: function() {
// We create an element with the html to mark. Give it a unique id
// so it can be removed later
let id = 'id' + (new Date()).getTime();
$('body').append(`<div id="${id}" style="hidden">${this.html}</div>`);
// Create a Mark instance on the new element
let markInstance = new Mark('#' + id);
// Mark the text with the search string. When the operation is complete,
// update the hightlighted text and remove the temporary element
markInstance.markRegExp(new RegExp(this.search, 'gmi'), {
done: () => {
this.highlightedHtml = $('#' + id)[0].innerHTML;
$('#' + id).remove();
},
acrossElements: true,
});
},
immediate: true
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.0/mark.js"></script>
<div id="demo">
<div>/ <input type="text" v-model="search"> /gmi</div>
<div v-html="highlightedHtml"></div>
</div>
&#13;