vue多个关键字高亮

效果图
效果图

<template>
  <div class='text_box'>
    <div
      :class="{hightLight:index%2!==0}"
      v-for="(item,index) in textData"
      :key="index"
    >
      <span >{{item}}</span> 
    </div>
  </div>
</template>

<script>
export default {
    // 多个关键字高亮
  data() {
    return {
      datas:"撒泼返回泡啊脚alohl/osdhjppjh嗯奥术大师多嗯啊啊奥术大师大叽啊发发叽喳喳",
      arrs:[
        {keyword:"啊啊"},
        {keyword:"嗯"},
        {keyword:"喳"},
      ],
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      let  arrs = []
      //根据关键字的数据格式改变for循环的内容
      for(let key in this.arrs){
        arrs.push(this.arrs[key].keyword)
      }
      // 根据arrs动态填写规则
      let reg = new RegExp(`(${arrs.join('|')})`,'g')

      let result = {};
      let currentIndex = 0, returnData = [];

      while ((result = reg.exec(this.datas))) {
        returnData.push(this.datas.slice(currentIndex, result.index));
        returnData.push(result[1]);
        currentIndex = result.index + result[0].length;
      }
      if (this.datas.length > currentIndex) {
        returnData.push(this.datas.slice(currentIndex, this.datas.length));
      }
      console.log(returnData);
      this.textData = returnData;
    }
  }
};
</script>

<style>
.text_box{
    display: flex;
    align-items: start;
    flex-wrap: wrap;
}
.hightLight {
  color: red;
}
</style>
Vue中实现多个关键字高亮、返回多个结果的模糊查询,可以使用正则表达式和Vue的computed计算属性来实现。 首先,将要查询的关键字以数组的形式保存下来,例如: ```javascript data() { return { keywords: ['Vue', '多关键字', '模糊查询'], articles: [ { title: 'Vue实现多关键字高亮和模糊查询', content: '...' }, { title: '使用Vue开发多关键字搜索功能', content: '...' }, ... ] } } ``` 接下来,使用computed计算属性来实现模糊查询和关键字高亮: ```javascript computed: { filteredArticles() { let articles = this.articles let keywords = this.keywords if (keywords.length > 0) { let regex = new RegExp(keywords.join('|'), 'gi') articles = articles.filter(article => { return article.title.match(regex) || article.content.match(regex) }) articles = articles.map(article => { article.title = article.title.replace(regex, '<span class="highlight">$&</span>') article.content = article.content.replace(regex, '<span class="highlight">$&</span>') return article }) } return articles } } ``` 上述代码中,先将要查询的关键字拼接成正则表达式,使用`|`作为分隔符,然后调用`match()`方法进行模糊匹配,将匹配到的文章进行关键字高亮处理,最后返回匹配到的文章数组。 最后,在模板中遍历`filteredArticles`数组,将文章渲染到页面上: ```html <template> <div> <div v-for="article in filteredArticles" :key="article.id"> <h2 v-html="article.title"></h2> <p v-html="article.content"></p> </div> </div> </template> ``` 在CSS中定义`.highlight`样式,用于显示高亮效果: ```css .highlight { color: red; font-weight: bold; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值