vue搜索关键字高亮
时间: 2023-06-22 10:24:32 浏览: 44
在Vue中实现搜索关键字高亮可以通过以下步骤:
1. 在Vue组件中定义一个data属性来存储搜索关键字;
2. 在模板中使用v-html指令将需要高亮的文本渲染到页面上,同时利用computed属性实现高亮效果;
3. 在computed属性中使用正则表达式匹配文本中的关键字,并用`<span>`标签将匹配到的关键字包裹起来,并加上样式。
下面是一个示例代码:
```html
<template>
<div>
<input type="text" v-model="keyword" placeholder="请输入关键字">
<p v-html="highlightText"></p>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段需要搜索的文本,可以试着输入关键字进行搜索',
keyword: ''
}
},
computed: {
highlightText() {
const reg = new RegExp(this.keyword, 'gi');
const highlighted = this.text.replace(reg, `<span class="highlight">${this.keyword}</span>`);
return highlighted;
}
}
}
</script>
<style>
.highlight {
color: red;
}
</style>
```
在上面的代码中,我们定义了一个data属性`keyword`来存储搜索关键字,然后在模板中使用v-html指令将需要高亮的文本渲染到页面上。在computed属性中,我们使用正则表达式匹配文本中的关键字,并用`<span>`标签将匹配到的关键字包裹起来,并加上样式。最后,在样式中定义了`.highlight`类来设置高亮文本的颜色。