点击打开视频讲解
<template>
<div id="app">
<h2>js搜索关键字高亮显示</h2>
<input type="text" v-model="value" @input="inputChange">
<ul>
<li v-for="(item,index) in list" :key="index" v-html="item.name"></li>
</ul>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
value:'',
list:[
{ name:'推荐1' },
{ name:'推荐2' },
{ name:'推荐3' },
{ name:'推荐4' },
{ name:'推荐5' },
]
}
},
mounted(){
},
methods:{
inputChange(){
this.list = [ //恢复最初的状态
{ name:'推荐1' },
{ name:'推荐2' },
{ name:'推荐3' },
{ name:'推荐4' },
{ name:'推荐5' },
]
console.log(this.value.split(''))
this.value.split('').forEach(data => {
console.log(data,'data');
this.list.forEach(item => {
if(item.name.indexOf(data) == -1) return;
let hightStr = `<span style="color:red;">${ data }</span>`
let str = new RegExp(data,'gi')
item.name = item.name.replace(str,hightStr)
})
})
}
}
}
</script>
<style scoped>
</style>
网友评论