vue三级联动,不发ajax请求

本文介绍了一个基于Vue框架的城市选择组件实现细节。该组件通过三级联动的方式让用户可以选择省份、城市及区县。文章提供了完整的组件代码,并展示了如何初始化数据以及监听用户的选择变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
<div class="city-select" id="city">
<select v-model="selectedProvince" name="province">
<option v-for="(item, index) in provinces"
v-if="item.level === 1"
:value="item">
{{ item.name }}
</option>
</select>
<select v-model="selectedCity" name="city">
<option
v-for="(item, index) in cities"
:value="item">
{{ item.name }}
</option>
</select>
<select v-model="selectedBlock" name="block">
<option
v-for="(item, index) in blocks"
:value="item">
{{ item.name }}
</option>
</select>
</div>
</template>
<script>
import provinces from './../../assets/js/city'
import Vue from 'vue'
export default {
name: 'city',
created() {
// 数据初始化,默认选中北京市,默认选中第一个;北京市数据为总数据的前18个
let beijing = this.provinces.slice(0, 19);
this.cities = beijing.filter(item => {
if (item.level === 2) {
return true
}
});
this.selectedCity = this.cities[0];
this.blocks = beijing.filter(item => {
if (item.level === 3) {
return true
}
});
this.selectedBlock = this.blocks[0]
},
watch: {
selectedProvince(newVal, oldVal) {
// 港澳台数据只有一级,特殊处理
if (newVal.sheng === '71' || newVal.sheng === '81' || newVal.sheng === '82') {
this.cities = [newVal];
this.blocks = [newVal]
} else {
this.cities = this.provinces.filter(item => {
if (item.level === 2 && item.sheng && newVal.sheng === item.sheng) {
return true
}
})
}
var _this = this;
// 此时在渲染DOM,渲染结束之后再选中第一个
Vue.nextTick(() => {
_this.selectedCity = _this.cities[0];
_this.$emit('input', _this.info)
})
},
selectedBlock() {
var _this = this;
Vue.nextTick(() => {
_this.$emit('input', _this.info)
})
},
selectedCity(newVal) {
// 选择了一个市,要选择区了 di是城市的代表,sheng
if (newVal.sheng === '71' || newVal.sheng === '81' || newVal.sheng === '82') {
this.blocks = [newVal];
this.cities = [newVal]
} else {
this.blocks = this.provinces.filter(item => {
if (item.level === 3 && item.sheng && item.sheng == newVal.sheng && item.di === newVal.di && item.name !== '市辖区') {
return true
}
})
}
var _this = this;
Vue.nextTick(() => {
_this.selectedBlock = _this.blocks[0];
// 触发与 v-model相关的 input事件
_this.$emit('input', _this.info)
})
}
},
computed: {
info() {
return {
province: this.selectedProvince,
city: this.selectedCity,
block: this.selectedBlock
}
}
},
data() {
return {
selectedProvince: provinces[0],
selectedCity: 0,
selectedBlock: 0,
cities: 0,
provinces,
blocks: 0
}
}
}
</script>
city.js部分格式

转载于:https://www.cnblogs.com/liuhuanwen/p/6770005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值