vue实现热门城市
实现热门城市功能
在Vue中实现热门城市功能,可以通过数据驱动的方式结合UI组件完成。以下是几种常见实现方式:
数据准备
定义热门城市数据数组,通常在组件的data或Vuex/store中管理:
data() {
return {
hotCities: [
{ id: 1, name: '北京' },
{ id: 2, name: '上海' },
{ id: 3, name: '广州' },
{ id: 4, name: '深圳' },
{ id: 5, name: '杭州' }
]
}
}
基础列表渲染
使用v-for指令渲染城市列表:
<div class="hot-city-container">
<div v-for="city in hotCities" :key="city.id" class="city-item">
{{ city.name }}
</div>
</div>
带交互的实现
添加点击事件处理:

methods: {
handleCityClick(city) {
this.$emit('city-selected', city)
// 或执行路由跳转
// this.$router.push(`/city/${city.id}`)
}
}
对应模板:
<div
v-for="city in hotCities"
:key="city.id"
class="city-tag"
@click="handleCityClick(city)">
{{ city.name }}
</div>
样式优化
建议使用弹性布局实现网格效果:

.hot-city-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.city-tag {
padding: 8px 15px;
background: #f5f5f5;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s;
}
.city-tag:hover {
background: #e0e0e0;
}
从后端获取数据
实际项目中通常从API获取数据:
async created() {
try {
const res = await axios.get('/api/hot-cities')
this.hotCities = res.data
} catch (error) {
console.error('获取热门城市失败', error)
}
}
组件化实现
对于复用场景,可封装为独立组件:
<!-- HotCities.vue -->
<template>
<div class="hot-cities">
<h3>热门城市</h3>
<div class="city-list">
<!-- 列表内容 -->
</div>
</div>
</template>
性能优化
对于大量城市数据,建议:
- 添加虚拟滚动
- 实现分页加载
- 使用keep-alive缓存组件
完整组件示例
<template>
<div class="hot-cities">
<h3 class="title">热门城市</h3>
<div class="city-container">
<span
v-for="city in cities"
:key="city.id"
class="city-item"
@click="selectCity(city)">
{{ city.name }}
</span>
</div>
</div>
</template>
<script>
export default {
props: {
cities: {
type: Array,
default: () => []
}
},
methods: {
selectCity(city) {
this.$emit('select', city)
}
}
}
</script>
<style scoped>
.hot-cities {
margin: 20px 0;
}
.title {
margin-bottom: 10px;
font-size: 16px;
color: #333;
}
.city-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.city-item {
padding: 6px 12px;
background: #f0f0f0;
border-radius: 4px;
cursor: pointer;
}
.city-item:hover {
background: #e0e0e0;
}
</style>






