vue3如何在setup中帅选对象的时候匹配关键字使其匹配的关键字改变颜色并且展示到模板上
时间: 2023-05-30 17:03:38 浏览: 108
可以使用Vue3中的响应式数据和计算属性来实现。
在setup函数中,定义一个响应式对象,用于存储过滤关键字。然后定义一个计算属性,用于根据过滤关键字筛选出匹配的数据,并将匹配的关键字标记为不同颜色。
最后,在模板中使用v-for指令循环展示筛选后的数据,并使用v-html指令将匹配的关键字渲染为不同颜色。
示例代码如下:
```html
<template>
<div>
<input type="text" v-model="filterText">
<ul>
<li v-for="item in filteredItems" v-html="highlight(item.text)"></li>
</ul>
</div>
</template>
<script>
import { reactive, computed } from 'vue';
export default {
setup() {
const items = [
{ id: 1, text: 'Vue.js' },
{ id: 2, text: 'React.js' },
{ id: 3, text: 'Angular' },
{ id: 4, text: 'Ember.js' },
{ id: 5, text: 'Backbone.js' },
];
const state = reactive({
filterText: '',
});
const filteredItems = computed(() => {
return items.filter(item => {
return item.text.toLowerCase().includes(state.filterText.toLowerCase());
});
});
const highlight = text => {
const regex = new RegExp(state.filterText, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
};
return {
state,
filteredItems,
highlight,
};
},
};
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
```
在上面的示例代码中,我们使用了一个计算属性filteredItems来根据过滤关键字筛选出匹配的数据。
在highlight方法中,我们使用正则表达式来匹配关键字,然后使用replace方法将匹配的关键字用span标签包裹起来,并添加highlight类来改变关键字的颜色。
最后,在模板中使用v-html指令将展示筛选后的数据,并将匹配的关键字渲染为不同颜色。