当前位置:首页 > VUE

vue实现picker联动

2026-01-17 11:14:35VUE

Vue 实现 Picker 联动

在 Vue 中实现 Picker 联动通常涉及多个选择器之间的数据依赖关系。以下是一种常见的实现方式:

数据准备

定义数据模型,包括所有可能的选择项和当前选中的值:

data() {
  return {
    provinces: [],
    cities: [],
    districts: [],
    selectedProvince: '',
    selectedCity: '',
    selectedDistrict: ''
  }
}

初始化数据

createdmounted 钩子中加载初始数据:

async mounted() {
  const res = await axios.get('/api/provinces')
  this.provinces = res.data
}

监听变化

使用 watch 监听选择变化并更新下级数据:

vue实现picker联动

watch: {
  selectedProvince(newVal) {
    if (newVal) {
      this.fetchCities(newVal)
      this.selectedCity = ''
      this.selectedDistrict = ''
    }
  },
  selectedCity(newVal) {
    if (newVal) {
      this.fetchDistricts(newVal)
      this.selectedDistrict = ''
    }
  }
}

获取下级数据

定义获取下级数据的方法:

methods: {
  async fetchCities(provinceId) {
    const res = await axios.get(`/api/cities?province=${provinceId}`)
    this.cities = res.data
  },
  async fetchDistricts(cityId) {
    const res = await axios.get(`/api/districts?city=${cityId}`)
    this.districts = res.data
  }
}

模板部分

在模板中使用 select 或自定义 Picker 组件:

vue实现picker联动

<select v-model="selectedProvince">
  <option value="">请选择省份</option>
  <option v-for="item in provinces" :value="item.id">{{ item.name }}</option>
</select>

<select v-model="selectedCity" :disabled="!selectedProvince">
  <option value="">请选择城市</option>
  <option v-for="item in cities" :value="item.id">{{ item.name }}</option>
</select>

<select v-model="selectedDistrict" :disabled="!selectedCity">
  <option value="">请选择区县</option>
  <option v-for="item in districts" :value="item.id">{{ item.name }}</option>
</select>

使用第三方组件库

如果使用 Element UI 等组件库,实现方式类似:

<el-cascader
  :options="options"
  v-model="selectedValues"
  @change="handleChange"
></el-cascader>

移动端 Picker 实现

对于移动端,可以使用 vant 的 Picker 组件:

<van-picker
  title="请选择"
  show-toolbar
  :columns="columns"
  @confirm="onConfirm"
  @cancel="onCancel"
/>

性能优化

对于大数据量的 Picker,建议:

  • 实现懒加载
  • 添加防抖处理
  • 使用虚拟滚动

以上方法可以根据具体需求进行调整和组合使用,实现不同场景下的 Picker 联动效果。

标签: vuepicker
分享给朋友:

相关文章

vue单页面实现登录

vue单页面实现登录

实现登录功能的基本流程 在Vue单页面应用中实现登录功能,通常需要以下几个关键步骤: 创建登录表单组件 使用Vue的模板语法创建包含用户名和密码输入框的表单,并绑定数据到组件的data属性。 <…

vue实现单据

vue实现单据

Vue 实现单据功能的方法 使用 Vue 实现单据功能通常涉及表单设计、数据绑定、验证和提交等环节。以下是具体实现方案: 表单设计与数据绑定 使用 Vue 的 v-model 指令实现表单数据的双向…

vue computed实现

vue computed实现

计算属性的基本用法 在Vue中,计算属性通过computed选项定义,用于声明依赖于其他属性的动态值。计算属性基于它们的依赖进行缓存,只有依赖发生变化时才会重新计算。 new Vue({ dat…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue实现列表

vue实现列表

Vue 实现列表的方法 在 Vue 中实现列表渲染通常使用 v-for 指令,可以动态生成多个元素。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 遍历数组,生成列表项。v-for 需要…

vue实现前端跳转

vue实现前端跳转

Vue 实现前端跳转的方法 在 Vue 中实现前端跳转通常使用 Vue Router,以下是几种常见的跳转方式: 声明式导航(模板中使用 <router-link>) 在模板中直接使用…