当前位置:首页 > VUE

vue实现选择联动

2026-02-19 02:07:20VUE

Vue 实现选择联动的方法

数据绑定与监听

在Vue中实现选择联动通常基于v-modelwatchcomputed属性。通过双向绑定第一个选择框的值,监听其变化动态更新第二个选择框的选项。

<template>
  <div>
    <select v-model="selectedProvince">
      <option v-for="p in provinces" :value="p.id">{{ p.name }}</option>
    </select>
    <select v-model="selectedCity">
      <option v-for="c in cities" :value="c.id">{{ c.name }}</option>
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      provinces: [{id: 1, name: '广东'}, {id: 2, name: '江苏'}],
      cities: [],
      selectedProvince: null,
      selectedCity: null
    }
  },
  watch: {
    selectedProvince(newVal) {
      this.cities = this.getCitiesByProvince(newVal)
    }
  },
  methods: {
    getCitiesByProvince(provinceId) {
      // 模拟根据省份获取城市
      const cityData = {
        1: [{id: 101, name: '广州'}, {id: 102, name: '深圳'}],
        2: [{id: 201, name: '南京'}, {id: 202, name: '苏州'}]
      }
      return cityData[provinceId] || []
    }
  }
}
</script>

使用计算属性优化

对于简单的联动逻辑,计算属性比watch更简洁:

vue实现选择联动

computed: {
  filteredCities() {
    return this.getCitiesByProvince(this.selectedProvince)
  }
}

多级联动实现

三级联动(如省-市-区)可通过嵌套数据结构和多级监听实现:

vue实现选择联动

watch: {
  selectedProvince() {
    this.cities = this.getCitiesByProvince(this.selectedProvince)
    this.selectedCity = null
    this.districts = []
  },
  selectedCity() {
    this.districts = this.getDistrictsByCity(this.selectedCity)
  }
}

异步数据加载

当选项数据需要从API获取时,使用async/await

methods: {
  async loadCities() {
    this.cities = await axios.get(`/api/cities?province=${this.selectedProvince}`)
  }
}

组件化封装

对于复用场景,可封装为独立组件:

<template>
  <cascade-select 
    :levels="['province', 'city', 'district']" 
    @change="handleChange"
  />
</template>

注意事项

  • 初始化时应设置默认选中项避免空值
  • 清除下级选项时需重置v-model绑定值
  • 大数据量时考虑虚拟滚动优化性能
  • 移动端可使用<picker-view>等专用组件

标签: vue
分享给朋友:

相关文章

vue实现微博印象

vue实现微博印象

实现微博印象功能的核心思路 微博印象功能通常指用户发布微博后,系统自动分析文本内容并提取关键词或标签,以可视化形式展示。Vue实现该功能需要结合文本分析、关键词提取和前端渲染技术。 文本分析与关键词…

vue实现visual

vue实现visual

Vue 实现可视化(Visual)的常见方法 在 Vue 中实现可视化通常涉及数据可视化库的集成,以下是几种主流方案: 使用 ECharts ECharts 是一个强大的 JavaScript 图表…

vue实现摘要

vue实现摘要

Vue 实现摘要的方法 在 Vue 中实现文本摘要功能通常涉及截取文本的前部分内容并添加省略号。可以通过计算属性、过滤器或自定义指令来实现。 计算属性实现 在 Vue 组件中定义一个计算属性,用于截…

vue实现erp

vue实现erp

Vue实现ERP系统的关键步骤 技术选型与架构设计 采用Vue 3 + TypeScript构建前端,搭配Pinia状态管理,Element Plus或Ant Design Vue作为UI框架。后端可…

vue实现浮标

vue实现浮标

Vue 实现浮动按钮(浮标) 使用 Vue 实现浮动按钮可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 定位和 Vue 组件 创建 Vue 组件并配合 CSS 固定定位实现浮动按钮:…

vue键盘实现

vue键盘实现

监听键盘事件 在Vue中监听键盘事件可以通过v-on指令或@缩写实现。常见的键盘事件包括keydown、keyup和keypress。例如监听回车键事件: <template> &l…