预实现效果,如图:
html(主要部分):
<div v-html="setKeyWord(content)" class="content-box"></div>
js (主要部分):
setKeyWord (str) {const reg = new RegExp(this.keyWord, 'g');return str.replace(reg, `<span style="color: red;">${this.keyWord}</span>`);}
全部代码:
<template><div class='box'><p class='tip'>输入关键词查询</p><input type="text" v-model="keyWord" placeholder="请输入关键字"><div v-html="setKeyWord(content)" class="content-box"></div></div></template><script>export default {name: '',components: {},data () {return {keyWord: '',content: '先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必能裨补阙漏,有所广益。'};},computed: {},watch: {},created () {},mounted () {},methods: {setKeyWord (str) {const reg = new RegExp(this.keyWord, 'g');return str.replace(reg, `<span style="color: red;">${this.keyWord}</span>`);}},}</script><style lang='scss' scoped>.box {padding: 40px;font-size: 16px;}input {height: 40px;width: 280px;padding: 0 8px;margin-bottom: 20px;font-size: 16px;border: 1px solid teal;border-radius: 6px;box-sizing: border-box;}.tip {font-size: 14px;color: #9d9d9d;}.content-box {width: 400px;margin: 0 auto;line-height: 2;text-align: left;}</style>