实现匹配搜索词高亮(Vue3)
1.使用插件实现(ohlight)
(1).下载插件
// pnpm
pnpm i ohlight
// npm
npm i ohlight
// yarn
yarn add ohlight
如果让选择版本就按照提示的版本选择
(2).基本使用
>1.(Vue3)的使用
首先在vite.config.js中加入以下代码:
export default defineConfig({plugins: [vue({template: {compilerOptions: {//将所有包含短横线的标签作为自定义元素处理isCustomElement: (tag) => tag.includes("-"),},},}),],
});
如果没用vite,那么在vue.config.js中加入以下代码:
//vue.config.js
module.exports = {chainWebpack:config => {config.module.rule('vue').use('vue-loader').tap(option => ({...options,compilerOptions:{//将所有以ion-开头的标签作为自定义元素处理isCustomElement:tag => tag.startsWith('ion-')}}))}
}
然后对于他的使用也很简单,如下:
<script setup>
import { oLight } from "ohlight";
import { ref, reactive } from "vue";const value = ref();
const lightFont = reactive(["唱", "rap", "跳", "篮球"]);//高亮文字数据
let style = JSON.stringify({color: 'red',background: 'aliceblue','font-style': 'oblique'
})
</script>
<template><div><input type="text" v-model="value" /><o-light :content="value" :keywords="lightFont.join(',')" :styles="style"></o-light></div>
</template><style scoped></style>
下面是一些关于插件的属性
Api
属性
属性名 | 类型 | 描述 | 默认值 |
---|---|---|---|
content | string |
文本内容 | - |
keywords | string |
关键词字符串,多个关键词使用'',' 隔开 |
- |
styles | string |
高亮关键字样式,仅支持序列化后的CSSStyleDeclaration 对象;注:涉及到驼峰写法的需要改写成 - 连接 ;如:fontStyle 需要写成 font-style |
- |
stableTime | string | number |
防抖时间,单位:(ms) | 200 |
事件
所有的事件内容均在event.detail
中。
事件名 | 类型 | 描述 | 默认值 |
---|---|---|---|
load | Function |
该方法在组件绘制完成并挂载后触发,返回当前组件实例,内容在event.detail中 ,可供操作dom 使用等 |
- |
connectedCallback | Function |
当自定义元素第一次被连接到文档 DOM 时被调用 | - |
disconnectedCallback | Function |
当自定义元素与文档 DOM 断开连接时被调用 | - |
adoptedCallback | Function |
当自定义元素被移动到新文档时被调用 | - |
attributeChangedCallback | Function |
当自定义元素的一个属性被增加、移除或更改时被调用。 | - |
浏览器支持情况
chrome | edge | firefox | opera | safari |
---|---|---|---|---|
53+ | 79+ | 63+ | 40+ | 10+ |
当然,关于这个插件也可以去他的官网参照,链接放在这里了:
(高亮划词插件链接)[https://www.npmjs.com/package/ohlight]
2.自己实现一个方法
<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue'
const activeObj = reactive({arrWords: ['唱', '跳', 'rap', '篮球']
})
const inputVal = ref('');
let { arrWords } = toRefs(activeObj);const brightenKeyword = (val: any, keyword: any) => {const Reg = new RegExp(keyword, 'i');const res = val.join('').replace(Reg, `<span style="color: #f4ea2a;">${keyword}</span>`)return res;
}
</script>
<template><div class="container"><input type="text" v-model="inputVal" /><div v-html="brightenKeyword(arrWords, inputVal)"> </div></div>
</template>