当前位置:首页 > VUE

vue实现切换城市

2026-01-08 13:24:09VUE

实现思路

通过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库时:

vue实现切换城市

<el-select v-model="selectedCity" @change="handleCityChange">
  <el-option
    v-for="city in cityList"
    :key="city"
    :label="city"
    :value="city"
  />
</el-select>

以上实现可根据具体项目需求进行组合或扩展,核心在于状态管理和变更后的数据更新机制。

标签: 城市vue
分享给朋友:

相关文章

代码实现vue

代码实现vue

创建Vue项目 使用Vue CLI快速初始化项目,确保已安装Node.js和npm/yarn: npm install -g @vue/cli vue create my-vue-project c…

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。例…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue实现抖动

vue实现抖动

Vue 实现抖动效果 在 Vue 中实现抖动效果可以通过 CSS 动画或 JavaScript 动画库来实现。以下是几种常见的方法: 使用 CSS 动画 通过定义 @keyframes 动画并在 V…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

自实现vue

自实现vue

实现 Vue 的核心功能 要实现一个简化版的 Vue,需要理解其核心功能:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤的分解: 数据响应式 Vue 使用 Object.define…