要在el-table的单元格中只修改特定字符的颜色,可以使用自定义模板和CSS样式来实现。以下是一个示例:

<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>

在上面的示例中,我们使用<el-table>组件来展示数据,并在姓名列中使用了自定义模板。在模板中,我们使用了highlightKeyword方法来将特定字符标记为红色。

highlightKeyword方法接受三个参数:text(单元格的内容),keyword(要标记的特定字符),color(标记的颜色)。该方法的实现逻辑如下:

  1. 首先,检查keyword是否为空,如果为空则直接返回text
  2. 使用RegExp构造函数创建一个全局不区分大小写的正则表达式。
  3. 使用split方法将text根据正则表达式拆分为一个数组。
  4. 遍历拆分后的数组,对于数组中的每个部分:
    • 如果不是最后一个部分(即特定字符后还有其他字符),则将当前部分用<span class="highlight">包装起来,并添加<span style="color: inherit">标签和特定字符。
    • 如果是最后一个部分,则只将当前部分用<span class="highlight">包装起来。
  5. 返回拼接后的结果数组。

最后,我们使用CSS样式.highlight来定义特定字符的颜色为红色

el-table中单元格的内容 只修改的颜色特定字符其他字符不动

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

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