<template>
  <el-table :data="tableData">
    <el-table-column prop="name" label="姓名">
      <template slot-scope="scope">
        <div class="cell-content">{{ highlightKeyword(scope.row.name, '特定字符', 'red') }}</div>
      </template>
    </el-table-column>
  </el-table>
</template>
<style>
.cell-content {
  white-space: nowrap; /* 防止内容换行 */
}

.highlight {
  color: red; /* 修改特定字符的颜色 */
}
</style>
<script>
export default {
  data() {
    return {
      tableData: [
        { name: '特定字符' },
        { name: '其他字符' },
        { name: '特定字符和其他字符' }
      ]
    }
  },
  methods: {
    highlightKeyword(text, keyword, color) {
      if (!keyword) {
        return text;
      }
      
      const regex = new RegExp(keyword, 'gi');
      const parts = text.split(regex);
      const result = [];

      parts.forEach((part, index) => {
        if (index !== parts.length - 1) {
          result.push(<span class="highlight">${part}</span>);
          result.push(<span style="color: inherit">${keyword}</span>);
        } else {
          result.push(<span class="highlight">${part}</span>);
        }
      });

      return result;
    }
  }
}
</script>
<p>在上面的示例中,我们使用<code>&lt;el-table&gt;</code>组件来展示数据,并在姓名列中使用了自定义模板。在模板中,我们使用了<code>highlightKeyword</code>方法来将特定字符标记为红色。</p>
<p><code>highlightKeyword</code>方法接受三个参数:<code>text</code>(单元格的内容),<code>keyword</code>(要标记的特定字符),<code>color</code>(标记的颜色)。该方法的实现逻辑如下:</p>
<ol>
<li>首先,检查<code>keyword</code>是否为空,如果为空则直接返回<code>text</code>。</li>
<li>使用<code>RegExp</code>构造函数创建一个全局不区分大小写的正则表达式。</li>
<li>使用<code>split</code>方法将<code>text</code>根据正则表达式拆分为一个数组。</li>
<li>遍历拆分后的数组,对于数组中的每个部分:
<ul>
<li>如果不是最后一个部分(即特定字符后还有其他字符),则将当前部分用<code>&lt;span class=&quot;highlight&quot;&gt;</code>包装起来,并添加<code>&lt;span style=&quot;color: inherit&quot;&gt;</code>标签和特定字符。</li>
<li>如果是最后一个部分,则只将当前部分用<code>&lt;span class=&quot;highlight&quot;&gt;</code>包装起来。</li>
</ul>
</li>
<li>返回拼接后的结果数组。</li>
</ol>
<p>最后,我们使用CSS样式<code>.highlight</code>来定义特定字符的颜色为红色。</p>
Element UI el-table 单元格特定字符颜色修改 - 高亮关键字技巧

原文地址: https://www.cveoy.top/t/topic/qfDR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录