Bootstrap

vue3搜索显示出对应的搜索结果,结果中与关键字对应的字体高亮

效果

vue3代码

<template>
  <div>
    <el-input v-model="title" @input="sea" style="width: 400px;border: 1px solid black;"></el-input>
    <ul v-for="item in newlist" :key="item.id">
        <li v-html="highlight(item.name)"></li>
    </ul>
  </div>
</template>

<script lang='ts' setup>
  import { computed, ref } from 'vue'
  let title=ref('')
  const sea=()=>{
    //搜索
    console.log(title.value);
  }
  const list=ref([
    {
      id:1,
      name:'自行车'
    },
    {
      id:2,
      name:'山地车'
    },
    {
      id:3,
      name:'公路车'
    },
    {
      id:4,
      name:'电动车'
    },
    {
      id:5,
      name:'苹果手机'
    },
    {
      id:6,
      name:'华为手机'
    },
    {
      id:7,
      name:'小米手机'
    }
  ])

  const newlist=computed(()=>{
    //如果未输入内容,则ul下不显示任何内容
    if(title.value=='') return;
    else{
      return list.value.filter(item=>item.name.includes(title.value))
    }
  })
  interface list{
    id:number,
    name:string
  }

  const highlight=(text:string)=>{
    if(!title.value) return text;
    //将输入的内容替换成span标签,并设置样式
    //正则表达式:gi 表示全局匹配,忽略大小写
    return text.replace(new RegExp(title.value,'gi'),`<span style="color:blue">${title.value}</span>`)
  }
 
</script>

<style lang='less' scoped>
</style>

;