Created
September 7, 2021 20:09
-
-
Save JeffreyWay/1a83fd57ffa576c0ec5f8f251d9108fd to your computer and use it in GitHub Desktop.
Simple Real-Time Search Highlighting Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<form> | |
<input | |
@input="setSearch($event.target.value)" | |
:value="search" | |
type="text" | |
placeholder="Search" | |
class="border p-1" | |
/> | |
</form> | |
<div class="mt-2"> | |
<p v-for="(line, index) in song" v-html="line" :key="index"></p> | |
</div> | |
</div> | |
</template> | |
<script> | |
import debounce from 'lodash/debounce'; | |
export default { | |
data() { | |
return { | |
lines: [ | |
'The itsy-bitsy spider', | |
'Climbed up the water spout', | |
'Down came the rain', | |
'And washed the spider out', | |
'Out came the sun', | |
'And dried up all the rain', | |
'And the itsy-bitsy spider', | |
'Climbed up the spout again', | |
], | |
search: '', | |
}; | |
}, | |
computed: { | |
song() { | |
if (!this.search) { | |
return this.lines; | |
} | |
return this.lines.map((line) => | |
line.replace( | |
this.escapedSearch, | |
'<mark class="bg-blue-500 text-white">$&</mark>' | |
) | |
); | |
}, | |
escapedSearch() { | |
return new RegExp(this.search.replace(/[.*?^${}()\[\]]/g, '\\$&'), 'i'); | |
}, | |
}, | |
methods: { | |
setSearch: debounce(function (value) { | |
this.search = value; | |
}, 200), | |
}, | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment