当前位置:首页 > 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中实现全局遮罩层可以通过多种方式完成,以下是几种常见的实现方法: 使用Vue组件创建遮罩层 创建一个遮罩层组件,通过全局注册或动态挂载的方式实现全局调用。以下是一个简…

vue 实现在线预览

vue 实现在线预览

Vue 实现在线预览的常见方法 使用 iframe 嵌入 通过 iframe 标签可以嵌入多种类型的文件,如 PDF、图片、网页等。需要确保文件地址可访问。 <template>…

vue实现分屏

vue实现分屏

Vue 实现分屏的方法 分屏功能通常用于展示多个独立内容区域,以下是几种常见的实现方式: 使用 CSS Grid 布局 通过 CSS Grid 可以轻松创建分屏布局,在 Vue 组件中直接应用样式…

vue全选实现

vue全选实现

Vue 全选实现方法 在 Vue 中实现全选功能通常涉及数据绑定和事件处理。以下是几种常见的实现方式: 基础实现方式 <template> <div> <…

vue 实现复选

vue 实现复选

Vue 实现复选功能 在 Vue 中实现复选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动收集用户选择的复选框值。…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: &l…