这是一个三级联动,写修改页面时,需要展现该条记录所在的“省”,“市”,“县”并默认选中,还要显示其他的“省”,“市”,“县”。最大误区:select的默认显示是:value而不是text。
1、在组件中的写法
<select name="province" id="province" @change="getCity()" ref="ref_province" v-model="selected.province">
<option value="0" selected>请选择省</option>
<option v-for="(v,i) in this.allProvince" :id="v.id" :value="v.name" :label="v.name" :key="v.id"></option>
</select>
<select name="city" id="city" @change="getDistrict()" ref="ref_city" v-model="selected.city">
<option value="0" selected>请选择市</option>
<option v-for="(v,i) in this.allCity" :id="v.id" :value="v.name" >{{v.name}}</option>
</select>
<select name="county" id="district" ref="ref_district" v-model="selected.district">
<option value="0" selected>请选择县</option>
<option v-for="(v,i) in this.allDistrict" :id="v.id" :value="v.name" >{{v.name}}</option>
</select>
2、在js中定义,变量。
data () {
return {
selected:{province:'0',city:'0',district:'0'},//默认省市县
allProvince: '',//所有省
allCity:'',
allDistrict:''
};
},
created(){
this.workDelId = this.upId;
this.isUpdate()//页面加载完就调用
},
methods:{
isUpdate(){//根据id的值判断,是修改页面还是添加页面
if(this.workDelId != ""){//id不为空表示修改页面,根据id值获取信息
this.workDetail()
}else {
this.getProvince()//id值为空表示添加页面,直接获取省接口
}
},
3、获取到当前信息的“省”,“市”,“县”
workDetail(){
var that = this;
this.apiPost(url+'project/inProjectinformation/detail',{'id':this.workDelId }).then(function (data) {
console.log(data)
that.selected.province = data.Return.province;
that.selected.city = data.Return.city;
that.selected.district = data.Return.district;
that.getProvince()//调用省接口
})
},
4、获取"省级"接口
getProvince(){
var that = this;
this.apiPost(url+"area/sysArea/province",{}).then(function (data) {
if(data.Status == '0'){
that.allProvince = data.Return;
for(let i=0;i<data.Return.length;i++){//获取默认选中省的id,查找该省份下的市
if(that.selected.province == data.Return[i].name){
that.selected.province = data.Return[i].name
that.getCity(data.Return[i].id)//调用 “市“ 接口
}
}
}
})
}
5、获取"市级"接口
getCity(proId){
if(proId == undefined){//如果省id不存在,表示不是从getProvince()方法里调用的,而是调用@change=“getCity()”
const all_pro=this.$refs.ref_province;
const index=all_pro.selectedIndex;
proId = all_pro.options[index].id //则获取当前选择省的id,
this.selected.city='0' //并让市显示为“请选择”
}
var that = this;
this.apiPost(url+"area/sysArea/city",{'parent':{'id':proId}}).then(function (data) {
if(data.Status == '0'){
that.allCity = data.Return;
for(let i=0;i<data.Return.length;i++){
if(that.selected.city == data.Return[i].name){
that.getDistrict(data.Return[i].id)
}
}
}
})
}
6、获取“县级”接口同上,依此类推。