vue3实现搜索高亮

vue3实现搜索高亮

原文:Vue3文本高亮 - 掘金 (juejin.cn)

思路

input 的文本进行转义处理(eacapeReg函数),v-html 就不能相信用户的一切输入,并且需要匹配 ** . ( ) ***** 等等特殊字符;

根据正则匹配 input 文本,replace 写入 html 代码;

v-html 渲染处理后的文本;

定义组件

c-highlightText.vue

<script setup lang="ts">
withDefaults(
  defineProps<{
    hText?: string //需要高亮文本
    text?: string //原本文本
    color?: string //高亮颜色
  }>(),
  { hText: '', text: '', color: '#409EFF' }
)

function brightenKeyword(hText: string, text: string, color: string) {
  if (text) {
    /**
     * 全局匹配、不区分大小写
     */
    const Reg = new RegExp(eacapeReg(hText), 'gi')
    return text.replace(Reg, function ($1) {
      return `<span style="color: ${color};">${hText === $1 ? hText : $1}</span>`
    })
  }
}

/**
 * 将 \ . ( ) 等等字符前面都加上 \
 * @param val string
 * @returns string
 */
function eacapeReg(val: string): string {
  return val
    .replace(/\\/g, '\\\\')
    .replace(/\(/g, '\\(')
    .replace(/\)/g, '\\)')
    .replace(/\./g, '\\.')
    .replace(/\+/g, '\\+')
    .replace(/\*/g, '\\*')
    .replace(/\$/g, '\\$')
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
    .replace(/\^/g, '\\^')
    .replace(/\|/g, '\\|')
    .replace(/\-/g, '\\-')
    .replace(/\{/g, '\\{')
    .replace(/\}/g, '\\}')
    .replace(/\?/g, '\\?')
    .replace(/\!/g, '\\!')
    .replace(/\,/g, '\\,')
}
</script>

<template>
  <div v-html="brightenKeyword(hText, text, color)"></div>
</template>

页面调用

  <input v-model="rSName" type="text " class="mt-2" @input="squery()" />
          <div v-for="(item, index) in rSnippet" :key="index" class="item">
            <c-highlightText
              :h-text="rSName"
              color="red"
              :text="item.name"
              class="text-xl font-medium text-center"></c-highlightText>
            <v-md-preview ref="preview" :text="item.text" />
          </div>
const squery = async () => {
  rSnippet.value = await (await snippetApi.GetContains(0, 'null', rSName.value, false)).data
}
posted @ 2022-11-29 09:46  少年。  阅读(358)  评论(0编辑  收藏  举报