工作中总会遇到些头疼的事,例如想在elememt ui中找个三级联动,结果发现没有,于是自己封装了一个。具体代码如下:
<template>
<div>
<p>
<el-select select v-model="sheng" placeholder = "请选择">
<el-option v-for="item in allsheng" :value="item" :key = "item">{{item}}</el-option>
</el-select>
省
<el-select v-model="shi" placeholder = "请选择" ref = "shi">
<el-option v-for="item in allshi" :value="item" :key = "item">{{item}}</el-option>
</el-select>
市
<el-select v-model="xian" placeholder = "请选择">
<el-option v-for="item in allxian" :value = "item" :key = "item">{{item}}</el-option>
</el-select>
区
</p>
</div>
</template>
<script>
export default{
data(){
return {
sheng : "",
shi : "",
xian : ""
}
},
computed : {
allsheng(){
console.log(this.sheng)
return citydata.map(item=>item.name);
},
allshi(){
console.log(this.shi)
if(this.sheng==''){
this.shi=''
}else{
return citydata.filter(item=>item.name == this.sheng)[0].city.map(item=>item.name);
}
},
allxian(){
console.log(this.xian)
if(this.sheng==''){
this.xian=''
}else{
var thecity = citydata.filter(item=>item.name == this.sheng)[0].city.filter(item=>item.name == this.shi)[0];
if(thecity){
return thecity.area;
}
return [];
}
}
},
watch : {
sheng(){
this.shi = "";
this.xian = "";
},
shi(){
this.xian ="";
}
}
}
</script>
city.js是省市区的json(从某网站上拔下来的,具体就不提供了),我在index.html中引入的
里面是这样子滴:
我这是在vue项目中用的,所有封装成了组件,希望对你有所帮助