SOURCE

<!--
  组件名称:keyWordHighlight
  highlightWord:需要高亮的字符
  str:字符串
-->
<template>
  <BaseToolTip placement="top" :rows="1" :content="str">
    <template v-for="(word, index) in getSplitStr">
      <span v-if="index % 2" style="color: #f00; --el-color-primary: #f00">{{ word }}</span>

      <template v-else>{{ word }}</template>
    </template>
  </BaseToolTip>
</template>
<script setup>
import { formatVal } from '@/utils/index';
import { computed, toRefs } from 'vue';

const props = defineProps({
  highlightWord: {
    type: String,
    required: true,
  },
  str: {
    type: String,
    required: true,
  },
});
const { highlightWord, str } = toRefs(props);
const getSplitStr = computed(() => {
  if (formatVal(str.value, '') && highlightWord.value !== '') {
    const arr = highlightWord.value
      .split(' ')
      .filter(Boolean)
      .sort((a, b) => (a.length > b.length ? -1 : 1))
      .map(item => item.replace(/([.^$*+?{}|()\[\]\\])/g, '\\$1'));
    const reg = new RegExp(`(${arr.join('|')})`, 'g');
    return `${str.value}`.split(reg);
  }
  return [];
});
</script>
console 命令行工具 X clear

                    
>
console