vue实现城市模糊查询
Vue 实现城市模糊查询
数据准备
准备城市数据列表,可以存储在组件的 data 中或通过 API 获取。例如:
data() {
return {
cities: ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '重庆'],
searchQuery: '',
filteredCities: []
}
}
监听输入变化
使用 v-model 绑定输入框的值,并通过 watch 或 computed 监听输入变化:
watch: {
searchQuery(newVal) {
this.filterCities(newVal)
}
}
实现模糊查询逻辑
通过字符串匹配或正则表达式实现模糊查询。以下是一个简单的实现:

methods: {
filterCities(query) {
if (!query) {
this.filteredCities = this.cities
return
}
this.filteredCities = this.cities.filter(city =>
city.toLowerCase().includes(query.toLowerCase())
)
}
}
模板部分
在模板中添加输入框和结果列表:
<template>
<div>
<input v-model="searchQuery" placeholder="输入城市名称" />
<ul>
<li v-for="city in filteredCities" :key="city">
{{ city }}
</li>
</ul>
</div>
</template>
使用第三方库优化
可以使用 lodash 的 debounce 函数优化性能,避免频繁触发查询:

import { debounce } from 'lodash'
methods: {
filterCities: debounce(function(query) {
// 模糊查询逻辑
}, 300)
}
高亮匹配部分
如果需要高亮显示匹配的部分,可以使用 v-html 和正则表达式替换:
methods: {
highlightMatch(city, query) {
const regex = new RegExp(query, 'gi')
return city.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
<li v-for="city in filteredCities" :key="city" v-html="highlightMatch(city, searchQuery)" />
样式优化
添加一些基础样式提升用户体验:
.highlight {
background-color: yellow;
font-weight: bold;
}
完整示例代码
以下是一个完整的 Vue 组件示例:
<template>
<div>
<input v-model="searchQuery" placeholder="输入城市名称" />
<ul>
<li v-for="city in filteredCities" :key="city" v-html="highlightMatch(city, searchQuery)" />
</ul>
</div>
</template>
<script>
import { debounce } from 'lodash'
export default {
data() {
return {
cities: ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '重庆'],
searchQuery: '',
filteredCities: []
}
},
created() {
this.filteredCities = this.cities
},
watch: {
searchQuery(newVal) {
this.filterCities(newVal)
}
},
methods: {
filterCities: debounce(function(query) {
if (!query) {
this.filteredCities = this.cities
return
}
this.filteredCities = this.cities.filter(city =>
city.toLowerCase().includes(query.toLowerCase())
)
}, 300),
highlightMatch(city, query) {
if (!query) return city
const regex = new RegExp(query, 'gi')
return city.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>





