vue实现picker联动
Vue 实现 Picker 联动
在 Vue 中实现 Picker 联动通常涉及多个选择器之间的数据依赖关系。以下是一种常见的实现方式:
数据准备
定义数据模型,包括所有可能的选择项和当前选中的值:
data() {
return {
provinces: [],
cities: [],
districts: [],
selectedProvince: '',
selectedCity: '',
selectedDistrict: ''
}
}
初始化数据
在 created 或 mounted 钩子中加载初始数据:
async mounted() {
const res = await axios.get('/api/provinces')
this.provinces = res.data
}
监听变化
使用 watch 监听选择变化并更新下级数据:
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 组件:
<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 联动效果。







