当前位置:首页 > 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库时:

<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中实现共享屏幕功能通常需要结合浏览器的getDisplayMedia API。以下是一个基础实现示例: <template> <div>…

vue为啥能实现监听

vue为啥能实现监听

Vue 实现监听的原理 Vue 的监听能力主要基于其响应式系统,该系统通过数据劫持和依赖收集实现。当数据变化时,系统能自动触发视图更新或执行回调函数。 核心机制:Object.definePrope…

vue实现打字机

vue实现打字机

Vue实现打字机效果 在Vue中实现打字机效果可以通过动态更新文本内容并添加延迟来实现。以下是几种常见的实现方法: 使用setInterval实现 <template> <di…

vue弹幕实现不重叠

vue弹幕实现不重叠

实现 Vue 弹幕不重叠的方法 CSS 定位与动画控制 通过绝对定位和动态计算弹幕轨道高度,确保弹幕在不同轨道上运行。每条弹幕占据固定高度的轨道,避免重叠。 // 弹幕轨道高度计算 const tr…

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mind…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…