vue3+ts-实现搜索关键词变红
warning:
这篇文章距离上次修改已过201天,其中的内容可能已经有所变动。
在Vue 3和TypeScript中,可以通过使用一个计算属性来处理搜索关键词并将其变红的需求。以下是一个简单的示例:
<template>
<div>
<input v-model="searchQuery" placeholder="Search..." />
<div v-html="highlightedContent"></div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const searchQuery = ref('');
const content = ref('This is a simple example content.');
const highlightedContent = computed(() => {
if (!searchQuery.value) {
return content.value;
}
const regex = new RegExp(searchQuery.value, 'gi');
return content.value.replace(regex, match => `<span class="highlight">${match}</span>`);
});
return {
searchQuery,
highlightedContent,
};
},
});
</script>
<style>
.highlight {
color: red;
}
</style>
在这个例子中,我们有一个搜索框和一个显示内容的div
。通过v-model
绑定的searchQuery
用于接收用户输入的搜索词。计算属性highlightedContent
根据searchQuery
的值和内容content
生成一个新的HTML字符串,其中匹配搜索词的部分被<span>
标签包裹,并应用了一个.highlight
类。在CSS中,.highlight
类设置了红色字体。
评论已关闭