Vue3文本高亮

1,002 阅读1分钟

需求背景:input中的文本在text中高亮

\

实现思路

  • 将 input 的文本进行转义处理(eacapeReg函数),v-html 就不能相信用户的一切输入,并且需要匹配 \  .   (   )   *  等等特殊字符;
  • 根据正则匹配 input 文本,replace 写入 html 代码;
  • 用 v-html 渲染处理后的文本;

组件代码

<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>
  <span v-html="brightenKeyword(hText, text, color)"></span>
</template>

Demo

<script setup lang="ts">
import highlightText from './components/highlightText.vue';

import { ref } from 'vue';
const search = ref('');
</script>

<template>
  <div class="flex vc">
    输入框<el-input v-model="search" class="w-100 ml-8"></el-input>
  </div>
  <div class="flex vc mt-4">
    文本显示
    <highlightText :hText="search" color="red" text="false" class="ml-8"
    ></highlightText>
  </div>
</template>