JS 实现关键字文本搜索 高亮显示

示例:

  •  利用字符串的 split 方法,通过搜索的关键字分割成数组

  •  在利用数组的 join 方法拼接成字符串

 我是利用mock的省份

 1 <template>
 2   <div class="home">
 3     <input type="text" v-model.trim="SerachValue">
 4     <button @click="serach">点击搜索</button>
 5     <ul>
 6       <li v-for="(item, index) in cityMEList" :key="index">
 7         <span v-html="item"></span>
 8       </li>
 9     </ul>
10   </div>
11 </template>
12 
13 <script>
14 import axios from 'axios'
15 export default {
16   components: {
17   },
18   data() {
19     return {
20       SerachValue: '',
21       cityMEList: []
22     };
23   },
24   created() {
25     
26   },
27   methods: {
28     serach() {
29       if(!this.SerachValue) {
30         return
31       }
32       this.cityMEList = []
33       axios.get("/cityMeunList").then(res => {
34       const { list } = res.data
35 
36       list.forEach(item => {
37         if(item.province.includes(this.SerachValue)) {
38           let data = JSON.parse(JSON.stringify(item))
39           let dataARr = data.province.split(this.SerachValue)       //字符串的方法先转成数组
40           let str = dataARr.join('<span style="color:red;">' + this.SerachValue + '</span>')   // 在转成字符串
41           this.cityMEList.push(str)
42         }
43       });
44       console.log(list)
45     })
46     }
47   }
48 }
原文地址:https://www.cnblogs.com/shun1015/p/14208021.html