vue中高亮p标签中的某一个字符串

循环后台返回的数据如下结构

 <div :key="num">
      <p class="sentence">
        {{ i.sentence }}
        <span>{{ i.source }}</span>
      </p>
      <p class="sentence">{{ i.senInterpret }}</p>
 </div>

其中i.sentence 是字符串"This is a pig" 渲染的页面上
This is a pig

有一个全局的变量 this.word = pig 的时候

要高亮 这个pig

阅读 2.8k
3 个回答

//高亮

hightlight(str) {
  const search = this.word;
  var subStr = new RegExp(search); // 匹配关键字正则
  let replaceString = '<span class="highlights-text">' + search + "</span>"; // 高亮替换v-html值
  let result = str.replace(subStr, replaceString);
  return result;
},

//建议封装成vue指令解决,不用全局搜索,影响范围小。

demo地址 http://jsrun.net/kAwKp
<template>
    <input type="radio" id="pig" value="pig" v-model="piked" />
        <label for="pig">pig</label>
        <input type="radio" id="dog" value="dog" v-model="piked" />
        <label for="dog">dog</label>
        <div>{{piked}}</div>
        <ul>
            <li v-hightlight="{text: item, search: piked}" v-for="item of list" :key="item"></li>
        </ul>
</template>
<script>

    function hightlight(str, search) {
        var subStr = new RegExp(search); // 匹配关键字正则
        let replaceString = '<span style="color:yellow">' + search + "</span>"; // 高亮替换v-html值
        let result = str.replace(subStr, replaceString);
        return result;
    }

    const app = Vue.createApp({
        template: '#dd1',
        setup () {
            const piked = Vue.ref('pig')
            const list = Vue.ref([
                'this is pig',
                'this is dog'
            ])
            return {
                piked,
                list
            }
        }
    })
    app.directive('hightlight', {
        mounted (el,binding, vnode) {
            const html = el.innerHTML
            const {text= '', search = ''} = binding.value || {}
            // console.log()
            if (text.includes(search)) {
                el.innerHTML = hightlight(text, search)
            } else {
                el.innerHTML = text
            }
        },
        updated (el, binding) {
            const html = el.innerHTML
            const {text= '', search = ''} = binding.value || {}
            if (text.includes(search)) {
                el.innerHTML = hightlight(text, search)
            } else {
                el.innerHTML = text
            }
        }
    })
    app.use(vant);
    app.mount('#app')


</script>
推荐问题
宣传栏