vue项目实现搜索内容变红色显示

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue项目实现搜索内容变红色显示

coderSlow   2022-12-24 我要评论

1、经过二次处理后数据的使用

核心思想就是对从后台搜索获取到的数据进行二次加工处理,来达到想要的效果

<ul class="content_box">
  <li class="content_item" v-for="(item, index) in contentListData" :key="index" @click="searchLinkDetails(item)">
    <div class="title" v-html="item.title"></div>
    <div class="content" v-html="item.originalContent"></div>
    <div class="time">{{item.publishTime}}</div>
  </li>
</ul>

2、data中要定义的数据参数

searchValue: '', // 搜索文本
contentListData: []

3、获取列表数据并二次处理数据

// 获取列表的方法
    async getDataList() {
      let params = {
        websiteId: 4,
        content: this.searchValue,
        current: this.currentPage,
        size: 10,
        timeRange: this.searchTimeCheck,
        searchRange: this.searchScopeCheck
      }
      let res = await searchList(params)
      this.contentListData = res.data.records
      this.total = res.data.total
      // 核心处理方法开始-----------------------------------------------》
      if (this.searchValue && this.searchValue.length > 0) {
        const reg = `/${this.searchValue}/g`;
        this.contentListData.forEach((item) => {
          item.title = item.title.replace(
            eval(reg),
            "<span style='color: red;'>" + this.searchValue + "</span>"
          );
          if (item.originalContent) {
            item.originalContent = item.originalContent.replace(
              eval(reg),
              "<span style='color: red;'>" + this.searchValue + "</span>"
            );
          }
        });
      }
      // 核心处理方法结束------------------------------------------------》
    },

总结核心代码和具体效果如下

1、数据二次处理的核心方法

if (this.searchValue && this.searchValue.length > 0) {
    const reg = `/${this.searchValue}/g`;
    this.contentListData.forEach((item) => {
      item.title = item.title.replace(
        eval(reg),
        "<span style='color: red;'>" + this.searchValue + "</span>"
      );
      if (item.originalContent) {
        item.originalContent = item.originalContent.replace(
          eval(reg),
          "<span style='color: red;'>" + this.searchValue + "</span>"
        );
      }
    });
}

2、实现效果

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们