Vue highlights the keywords searched by the element search box

final effect:

method one: 

Add the following code to the getList() query event:

          // 获取搜索框和表格元素
          const searchInput = this.queryParams.name;
          const table = document.querySelector('#data-table'); 
          // 监听搜索框输入事件
          // searchInput.addEventListener('input', () => {
          // 获取搜索关键字
          const keyword = searchInput; 
          // 如果搜索关键字为空,移除所有高亮样式
          if (!keyword) {
            table.querySelectorAll('.highlight').forEach(el => {
              el.classList.remove('highlight');
            });
            return;
          } 
          // 遍历表格中的每个单元格
          table.querySelectorAll('td').forEach(td => {
            // 获取单元格文本内容
            const cellText = td.textContent.trim().toLowerCase();

            // 如果单元格内容包含搜索关键字,添加高亮样式
            if (cellText.includes(keyword)) {
              // 将匹配到的关键字替换为带有高亮样式的文本
              const highlightedText = cellText.replace(new RegExp(keyword, 'gi'), match => `<span class="highlight">${match}</span>`);
              td.innerHTML = highlightedText;
            } else {
              // 移除高亮样式
              td.innerHTML = cellText;
            }
          });
          // });

style:

/deep/ .el-table__row .highlight {
  background: yellow !important;
}

Method Two:

// 搜索框
<div @keyup.enter="search">    
	<el-input
        :placeholder="请输入搜索内容"
        prefix-icon="el-icon-search"
        v-model.trim="searchData"
    >
    </el-input>
</div>
// 表格
<el-table :data="searchTableDate" height="auto" style="width: 99%; margin: auto">
    <el-table-column type="index" width="50"> </el-table-column>
    <el-table-column prop="name" :label="文件名">
        <template slot-scope="scope">
            // 核心
            <span  v-html="showData(scope.row.name, searchData)"></span>
        </template>
    </el-table-column>
</el-table>
// 替换关键字
 showData(val, searchData) {
    // 不区分大小写  const Reg = new RegExp(searchData, 'i');
    // 全局替换  const Reg = new RegExp(searchData, 'g');
    const Reg = new RegExp(searchData, 'ig');
    if (val) {
        // 注意 这里推荐使用正则占位符$& 不使用${searchData}  因为当这里使用正则表达式(i)不区分大小写时,如果你的文本是大写,搜索的关键字是小写,匹配结果会替换掉大写的文本
        // const res = val.replace(Reg, `<span style="background-color: yellow;">${searchData}</span>`);
        const res = val.replace(Reg, `<span style="background-color: yellow;">$&</span>`);
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_43770056/article/details/130168275