掘金文章归档 · 第 61 篇 CSS 布局系列 6/9 搜索高亮 · Vue3

前端实现搜索文字变蓝

replaceAll 匹配关键词 + v-html 渲染高亮标签

原文作者:随意_(掘金) | juejin.cn/post/7406899773795926027 | 发布于 2024-08-26 | 阅读 381 · 约 1 分钟

0背景

我们在开发功能时候,很多时候会涉及到搜索,文本或者下拉的模块,如果匹配到对应文字,则匹配到的文字变蓝,效果如下,比如微信的效果。

1原理

正则匹配对应文字,增加特殊标记,标蓝。

原理:replaceAll 匹配对应文字,借助 vue 中的 v-html 来实现特殊标识。

2Vue3 写法及效果如下

<template>
  <div class="w-40">
    <el-input v-model="input" placeholder="请输入内容"></el-input>
    <h3 v-for="item in conList" :key="item.key" v-html="item.label"></h3>
  </div>
</template>
<script lang="ts" setup>
const input = ref();

const conList = computed(() => {
  return list.value.map(item => {
    return {
      ...item,
      label: item.label.includes(input.value) ? item.label.replaceAll(input.value, `<span style="color:red;">${input.value}</span>`) : item.label
    };
  });
});

const list = ref([
  {
    label: "张三丰张",
    key: "1"
  },
  {
    label: "张无忌",
    key: "2"
  },
  {
    label: "白眉鹰王",
    key: "3"
  },
  {
    label: "韦一笑",
    key: "4"
  },
  {
    label: "金毛狮王",
    key: "55"
  }
]);
</script>
<style lang="scss" scoped>
.w-40 {
  width: 40%;
}
</style>
截图占位:Vue3 输入关键词后列表匹配文字变红效果

3纯 Html 写法,可参考如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>搜索并高亮显示</title>
    <style>
        .highlight {
            color: red;
        }
    </style>
</head>

<body>
    <div id="content">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
        magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <input type="text" id="search" placeholder="Search text...">

    <script>
        document.getElementById('search').addEventListener('input', function () {
            var searchTerm = this.value.toLowerCase();
            var content = document.getElementById('content');
            if (searchTerm) {
                content.innerHTML = content.textContent.replace(new RegExp(searchTerm, 'gi'), match => `<span class="highlight">${match}</span>`);
            } else {
                content.innerHTML = content.textContent;
            }
        });
    </script>
</body>

</html>
⚠️ 使用 v-html / innerHTML 渲染用户输入时,注意 XSS 风险。生产环境建议先对关键词做转义(如替换 < > 等字符),再套高亮标签。
📌 核心三步:匹配关键词 → 包一层带颜色/class 的标签 → 用 v-html / innerHTML 渲染出来。