Vue中的Table搜索高亮

/ vue / 没有评论 / 156浏览

背景

实现table组件中的搜索高亮

重要参数 v-model 声明

export default {
  data() {
    return {
      // 搜索
      queryInfo: {
        query: '',
      },
      // 后台表格数据
      receiverInfos: [],
      // loading 效果
      loading:false,
    };
  }

Demo

Code

template部分

// 搜索按钮部分
                      <el-input prefix-icon="el-icon-search" placeholder="XXX" v-model="queryInfo.query" clearable @clear="getSearchInfo()">
                        <el-button icon="el-icon-search"></el-button>
                      </el-input>

<el-table
            v-loading="loading"
            element-loading-text="🐒  玩命加载中..."
            element-loading-spinner="el-icon-loadeding"
            element-loading-background="rgba(0, 0, 0, 0.6)"
            :default-sort = "{prop: 'UpdatedAt', order:'descending'}"
            :highlight-current-row=true
            :stripe=true
            :show-header=true
            :header-cell-style="{background:
            '#f1f0f0',color:'#1b1f1e'}"
            :data="receiverInfos"
            id="table-id"
            style="width: 100%">
            <el-table-column :show-overflow-tooltip="true" label="XX名称" prop="project_name" width="150">
              <template slot-scope= "scope" ><span class= "col-cont" v-html=" Highlight( scope.row.project_name)" ></span ></template >
          </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="XX套餐" prop="project_tpl" width="150">
              <template slot-scope= "scope" ><span class= "col-cont" v-html=" Highlight( scope.row.project_tpl)" ></span ></template >
            </el-table-column>
            <el-table-column
              align="right">
              <template slot-scope="scope">
                <el-button size="mini" type="info" @click="ViewInfo(scope.$index, scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

scripts部分

  computed: {
    // 实时监听表格
    receiverInfos: function() {
      const search = this.queryInfo.query
      if (search) {
        return this.receiverInfos.filter( dataNews => {
          return Object.keys(dataNews). some( key => {
            return String(dataNews[key]). toLowerCase(). indexOf(search) > - 1
          })
        })
      }
      return this.receiverInfos
    }
  },
      methods: {
    // 高亮
    Highlight( val) {
      val = val + '';
      // 检测值是否为空
      if ( val.indexOf( this.queryInfo.query) !== - 1 && this. search !== '') {
        return val.replace( this.queryInfo.query, '<font color="#409EFF">' + this.queryInfo.query + '</font>')
      } else {
        return val
      }
    },
      }

data部分

export default {
  data() {
    return {
      // 搜索
      queryInfo: {
        query: '',
      },
      // 后台表格数据
      receiverInfos: [],
      // loading 效果
      loading:false,
    };
  },