vue实现切换城市
实现思路
通过Vue的状态管理(如Vuex或Pinia)存储当前城市数据,结合下拉菜单或选项卡组件实现城市切换功能。切换时更新状态并触发相关数据重新加载。
核心代码实现
1. 状态管理(以Pinia为例)
// stores/city.js
import { defineStore } from 'pinia'
export const useCityStore = defineStore('city', {
state: () => ({
currentCity: '北京',
cityList: ['北京', '上海', '广州', '深圳']
}),
actions: {
setCurrentCity(city) {
this.currentCity = city
// 这里可以添加城市切换后的逻辑,如API请求
}
}
})
2. 城市选择组件
<template>
<div class="city-selector">
<select v-model="selectedCity" @change="handleCityChange">
<option v-for="city in cityList" :key="city" :value="city">
{{ city }}
</option>
</select>
<span>当前城市:{{ currentCity }}</span>
</div>
</template>
<script setup>
import { useCityStore } from '@/stores/city'
import { storeToRefs } from 'pinia'
const cityStore = useCityStore()
const { currentCity, cityList } = storeToRefs(cityStore)
const selectedCity = ref(currentCity.value)
const handleCityChange = () => {
cityStore.setCurrentCity(selectedCity.value)
}
</script>
高级实现方案
本地缓存城市选择
// 在Pinia的action中添加localStorage持久化
setCurrentCity(city) {
this.currentCity = city
localStorage.setItem('selectedCity', city)
}
// 初始化时读取
state: () => ({
currentCity: localStorage.getItem('selectedCity') || '北京'
})
基于地理定位的自动切换
// 在组件中调用浏览器定位API
navigator.geolocation.getCurrentPosition(
(position) => {
// 调用逆地理编码API获取城市名称
fetchCityName(position.coords).then(city => {
cityStore.setCurrentCity(city)
})
},
(error) => console.error(error)
)
注意事项
- 城市数据建议通过API动态获取,硬编码仅适用于演示
- 移动端可考虑使用Picker组件替代select
- 切换城市后需要重新加载地理位置相关数据
- 考虑添加城市搜索功能,当城市数量较多时
组件库推荐方案
使用Element Plus等UI库时:
<el-select v-model="selectedCity" @change="handleCityChange">
<el-option
v-for="city in cityList"
:key="city"
:label="city"
:value="city"
/>
</el-select>
以上实现可根据具体项目需求进行组合或扩展,核心在于状态管理和变更后的数据更新机制。







