1. 程式人生 > >vue.js實現省市區三級聯動

vue.js實現省市區三級聯動

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>vue實現省市級三級聯動</title>
<script src="vue.min.js"></script>

</head>
<body>
<div id="my">
{{province}}
<select v-model="province" @change="gengxin1(),gengxin2()">
<option v-for="item in list" >{{item.name}}</option>
</select>
<select v-model="citys" @change="gengxin2()" >
<option v-for="item in city" >{{item.city}}</option>
</select>
<select v-if="qu.length>0" v-model="dirst">
<option v-for="item in qu">{{item}}</option>
</select>
</div>

<script>
window.onload=function(){
new Vue({
el:'#my',
data:{
province:'安徽省',
city:[],
citys:'合肥市',
dirst:'蜀山區',
qu:[],
list:[
{name:'安徽省',
sub:[
{city:'合肥市',
qu:['蜀山區','廬陽區','瑤海區']
},
{city:'亳州市',
qu:['渦陽縣','蒙城縣','譙城區']
}
]},
{name:'浙江省',
sub:[
{city:'杭州市',
qu:['請選擇','西湖區 ','拱墅區']
},
{city:'金華市',
qu:['婺城區','譙城區']
}
]}
]
},
methods:{
gengxin1:function(){
self=this;
// forEach() 方法用於呼叫陣列的每個元素,並將元素傳遞給回撥函式。 item為當前元素
this.list.forEach(function(item,index){
// console.log(item);
// 當前元素裡的省跟province裡的值相同 就可以把當前item裡面的sub 追加到 二級城市
if(item.name==self.province){
self.city=item.sub
}

});
self.citys=self.city[0].city;

},
gengxin2:function(){

self=this;
// forEach() 方法用於呼叫陣列的每個元素,並將元素傳遞給回撥函式。 item為當前元素
this.city.forEach(function(item,index){
// console.log(item.city);
// 當前元素裡的省跟province裡的值相同 就可以把當前item裡面的sub 追加到 二級城市
if(item.city==self.citys){
self.qu=item.qu
}
});
//console.log(self.qu[0]);
self.dirst=self.qu[0]; console.log(this.qu); }, mounted:function(){ this.gengxin1(); }// beforeMount:function(){// //沒有執行//// this.gengxin1();// } } }) }; </script></body></html>