vue中,如何实现这个搜索出来的的内容加上高亮

vue中,如何实现给搜索出来的内容,单独的文字加上高亮,如下图所示

img

参考GPT的回答和自己的思路,vue中,如何实现这个搜索出来的的内容加上高亮代码如下所示:

<template>
  <div>
    <input v-model="keyword" placeholder="搜索...">
    <ul>
      <li v-for="item in searchResult" :key="item.id">
        <span v-html="highlightKeyword(item.title)"></span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      items: [
        { id: 1, title: 'Vue.js is a progressive JavaScript framework' },
        { id: 2, title: 'Vue.js makes building complex web applications a breeze' },
        { id: 3, title: 'Vue.js is easy to learn and use' }
      ]
    }
  },
  computed: {
    searchResult() {
      if (!this.keyword) {
        return this.items
      }
      const pattern = new RegExp(this.keyword, 'gi')
      return this.items.filter(item => item.title.match(pattern))
    }
  },
  methods: {
    highlightKeyword(title) {
      if (!this.keyword) {
        return title
      }
      const pattern = new RegExp(this.keyword, 'gi')
      const matched = title.match(pattern)
      if (!matched) {
        return title
      }
      const highlighted = title.replace(pattern, `<span class="highlight">${matched[0]}</span>`)
      return highlighted
    }
  }
}
</script>

<style>
.highlight {
  background-color: yellow;
  color: black;
}
</style>

以下是实现代码的完整思路,可以帮助您理解,
1.首先,在模板中定义一个用于展示搜索结果的列表:

<ul>
  <li v-for="item in searchResult" :key="item.id">
    <span v-html="highlightKeyword(item.title)"></span>
  </li>
</ul>

2.在Vue实例中定义一个方法highlightKeyword,该方法接收一个字符串参数,用于将关键字高亮显示。该方法的实现如下:

methods: {
  highlightKeyword(title) {
    if (!this.keyword) {
      return title
    }
    const pattern = new RegExp(this.keyword, 'gi')
    const matched = title.match(pattern)
    if (!matched) {
      return title
    }
    const highlighted = title.replace(pattern, `<span class="highlight">${matched[0]}</span>`)
    return highlighted
  }
}

在上述代码中,首先判断keyword是否存在,如果不存在则返回原始字符串title。如果keyword存在,则使用正则表达式创建一个不区分大小写的匹配模式,然后在title中查找匹配的关键字,并将其用标签包裹起来,同时为该标签添加highlight类,以便后续可以在样式表中为它设置高亮效果。

3.最后,在样式表中定义highlight类的样式,用于将高亮文本呈现为黄色背景、黑色文字:

.highlight {
  background-color: yellow;
  color: black;
}

回答不易,还请采纳!!!

“Devil组”引证GPT后的撰写:

  • 在Vue中实现给搜索出来的内容单独的文字加上高亮,可以使用Vue的模板语法和计算属性。假设搜索关键字存储在searchKeyword变量中,搜索结果列表存储在searchResult变量中,我们可以创建一个计算属性来对搜索结果列表中的文本进行高亮处理。

以下是实现方法:

  • 使用v-for指令遍历搜索结果列表,对于每一项,使用v-html指令将其渲染成HTML。
  • 在计算属性中,使用正则表达式匹配搜索关键字,并将匹配到的文本用标签包裹起来,并给标签添加highlight类名。
  • 在CSS中定义highlight类名,为高亮的文本添加样式。

具体实现代码如下:

<template>
  <div>
    <div>
      <label>搜索框:</label>
      <input type="text" v-model="searchKeyword" />
    </div>
    <div>
      <label>选择教师</label>
      <ul>
        <li v-for="item in searchResult" v-html="highlight(item)"></li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      teacherList: [
        '马明亮',
        '黎明',
        '王明明',
        '周明辉',
      ],
    };
  },
  computed: {
    searchResult() {
      if (!this.searchKeyword) {
        return this.teacherList;
      }
      const regex = new RegExp(this.searchKeyword, 'gi');
      return this.teacherList.filter((item) => {
        return item.match(regex);
      });
    },
  },
  methods: {
    highlight(text) {
      if (!this.searchKeyword) {
        return text;
      }
      const regex = new RegExp(this.searchKeyword, 'gi');
      const result = text.replace(regex, '<span class="highlight">$&</span>');
      return result;
    },
  },
};
</script>

<style scoped>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>


highlight方法用来对搜索结果进行高亮处理,它接收一个文本参数,使用正则表达式匹配搜索关键字,并将匹配到的文本用标签包裹起来,添加highlight类名,然后返回高亮处理后的文本。

  • 在模板中,使用v-for指令遍历搜索结果列表,对于每一项,使用v-html指令将其渲染成HTML。v-html指令会将highlight方法返回的HTML代码插入到DOM中,从而实现了搜索结果的高亮处理。
  • 最后,在CSS中定义highlight类名,为高亮的文本添加样式,比如黄色背景和粗体字。

参考GPT和自己的思路:在Vue中实现搜索栏联想词高亮的方法有很多种,以下是一种比较常见的做法:

在模板中使用v-html指令将匹配到的关键词进行高亮。

<template>
  <div>
    <input type="text" v-model="searchText" @input="search" />
    <ul>
      <li v-for="(item, index) in searchResult" :key="index" v-html="highlight(item)"></li>
    </ul>
  </div>
</template>


在上面的例子中,我们使用了v-html指令来将搜索结果进行渲染,并使用highlight方法将匹配到的关键词进行高亮。

实现highlight方法,用于高亮匹配到的关键词。

export default {
  data() {
    return {
      searchText: "",
      searchResult: [],
      highlightClass: "highlight",
    };
  },
  methods: {
    search() {
      // 处理搜索逻辑,获取搜索结果
      // ...

      this.searchResult = searchResult;
    },
    highlight(str) {
      // 使用正则表达式匹配关键词
      const regex = new RegExp(`(${this.searchText})`, "ig");
      return str.replace(regex, `<span class="${this.highlightClass}">$1</span>`);
    },
  },
};

在上面的例子中,我们实现了highlight方法,用于将匹配到的关键词进行高亮。我们使用了正则表达式来匹配关键词,并使用replace方法将匹配到的关键词替换为包含标签的字符串,从而实现高亮效果。

在CSS样式中定义高亮的样式。

.highlight {
  color: red;
  font-weight: bold;
}

在上面的例子中,我们定义了.highlight样式,用于设置高亮的颜色和字体加粗效果。

这样,当用户在搜索栏输入关键词后,搜索结果中包含该关键词的部分就会被高亮显示。请注意,使用v-html指令时需要谨慎防止XSS攻击。在实际应用中,应该对输入的内容进行过滤和转义,以确保安全性。


const arr = ["apple", "banana", "cherry", "date"];  //搜索后的数组
            const keyword = "an";  //搜索关键字
            const regex = new RegExp(keyword, "gi");
            arr.forEach((item, index) => {
              arr[index] = item.replace(regex, `<span class="highlight">${keyword}</span>`);
            });
            console.log(arr);  //处理后的数组

正则替换 就行 ,给 加个 元素写上 样式
https://blog.csdn.net/weixin_44058725/article/details/116274575

在 Vue 中实现搜索结果高亮的方式可以通过使用一个自定义指令来实现。以下是实现的步骤:

创建一个名为 highlight 的自定义指令。

Vue.directive('highlight', {
  // 在元素被绑定时调用
  bind: function (el, binding) {
    let search = binding.value;
    let reg = new RegExp(search, 'gi');
    let content = el.innerHTML;
    el.innerHTML = content.replace(reg, '<span class="highlight">' + search + '</span>');
  }
});



在需要高亮的元素上使用该指令,并将搜索关键字作为指令的值传递进去。

<!-- 在需要高亮的元素上使用 highlight 指令 -->
<p v-highlight="searchTerm">{{ item }}</p>



在上述代码中,searchTerm 是搜索关键字,item 是需要被搜索的内容。

在 CSS 样式表中定义 .highlight 样式。

.highlight {
  background-color: yellow;
}


上述代码定义了高亮的背景颜色为黄色。

这样,当搜索关键字出现在需要搜索的内容中时,就会使用上述指令将搜索关键字高亮显示。

在Vue中可以使用v-html指令和正则表达式来实现搜索关键字高亮显示。具体实现步骤如下:

1.在搜索结果中使用v-html指令,将匹配到的文本内容捆绑
2.使用正则表达式,将搜索关键字替换为带有高亮样式的HTML标签。

以下是实现代码的示例:

<template>
  <div>
    <input v-model="searchKeyword" @input="search" placeholder="请输入搜索关键字" />
    <ul>
      <li v-for="teacher in filteredTeachers" :key="teacher.id" v-html="teacher.highlightedName"></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      teachers: [
        { id: 1, name: "明" },
        { id: 2, name: "马明亮" },
        { id: 3, name: "黎明" },
        { id: 4, name: "王明明" },
        { id: 5, name: "王嘉明" },
        { id: 6, name: "周明辉" },
      ],
      searchKeyword: "",
    };
  },
  computed: {
    // 过滤后的教师列表
    filteredTeachers() {
      return this.teachers.map((teacher) => ({
        id: teacher.id,
        name: teacher.name,
        highlightedName: this.highlightKeyword(teacher.name), // 添加高亮标签后的教师姓名
      })).filter((teacher) => teacher.highlightedName !== ""); // 过滤掉不匹配的教师
    },
  },
  methods: {
    // 搜索关键字高亮处理
    highlightKeyword(name) {
      if (!this.searchKeyword) {
        return name;
      }
      const regex = new RegExp("(" + this.searchKeyword + ")", "gi");
      return name.replace(regex, "<span class='highlight'>$1</span>");
    },
    // 搜索
    search() {
      // 进行搜索操作
    },
  },
};
</script>

<style scoped>
.highlight {
  color: red;
  font-weight: bold;
}
</style>


在上述代码中,searchKeyword变量用于存储用户输入的搜索关键字,filteredTeachers计算属性用于对教师列表进行过滤,同时对每个教师的姓名进行高亮处理。highlightKeyword方法使用正则表达式将搜索关键字替换为带有高亮样式的HTML标签,然后将处理后的字符串作为教师姓名的高亮显示内容。在样式中,定义.highlight类的样式为高亮颜色和加粗效果。