名字筛选用vue实现
实现名字筛选的Vue组件
创建一个Vue组件实现名字筛选功能,可以通过输入框输入关键词实时筛选匹配的名字列表。
模板部分
<template>
<div class="name-filter">
<input
v-model="searchTerm"
placeholder="输入名字关键词"
class="filter-input"
/>
<ul class="name-list">
<li v-for="name in filteredNames" :key="name">
{{ name }}
</li>
</ul>
</div>
</template>
脚本部分

<script>
export default {
data() {
return {
searchTerm: '',
names: [
'张三',
'李四',
'王五',
'赵六',
'钱七',
'孙八'
]
}
},
computed: {
filteredNames() {
return this.names.filter(name =>
name.toLowerCase().includes(this.searchTerm.toLowerCase())
)
}
}
}
</script>
样式部分
<style scoped>
.name-filter {
max-width: 300px;
margin: 20px auto;
}
.filter-input {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
.name-list {
list-style: none;
padding: 0;
}
.name-list li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
优化筛选功能
增加更复杂的筛选逻辑,如支持拼音首字母匹配:

computed: {
filteredNames() {
const term = this.searchTerm.toLowerCase()
return this.names.filter(name => {
const lowerName = name.toLowerCase()
return lowerName.includes(term) ||
this.getPinyinInitials(name).includes(term)
})
}
},
methods: {
getPinyinInitials(name) {
// 简单实现拼音首字母匹配
const pinyinMap = {
'张': 'z', '三': 's',
'李': 'l', '四': 's',
'王': 'w', '五': 'w',
'赵': 'z', '六': 'l',
'钱': 'q', '七': 'q',
'孙': 's', '八': 'b'
}
return name.split('').map(char => pinyinMap[char] || '').join('')
}
}
使用第三方拼音库
为获得更准确的拼音匹配,可以引入pinyin-pro等专业库:
import pinyin from 'pinyin-pro'
methods: {
getPinyinInitials(name) {
return pinyin(name, { pattern: 'first', toneType: 'none' })
}
}
添加防抖优化
为防止频繁触发筛选,可以添加防抖功能:
import { debounce } from 'lodash'
computed: {
filteredNames: debounce(function() {
const term = this.searchTerm.toLowerCase()
return this.names.filter(name =>
name.toLowerCase().includes(term)
)
}, 300)
}
支持异步数据加载
当名字列表需要从API获取时:
data() {
return {
searchTerm: '',
names: [],
isLoading: false
}
},
async created() {
this.isLoading = true
this.names = await fetchNamesFromApi()
this.isLoading = false
}






