<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<ol>
<li v-for="site in sites">
{{ site.name }}
</li>
</ol>
<div>
<span>所在区域</span>
<select name="" v-model="countryName" @change="change_select">
<option v-for="(item,index) in area" v-bind:value="item.country">{{item.country}}</option>
</select>
<select name="" v-model="cityName">
<option v-for="(item,index) in cityNames" v-bind:value="item">{{item}}</option>
</select>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
sites: [{
name: 'Runoob'
},
{
name: 'Google'
},
{
name: 'Taobao'
}],
countryName:"",
cityName:"",
cityNames:[],
area:[
{
"country":"美国",
"city":["纽约","洛杉矶","旧金山","西雅图","波士顿","休斯顿","圣地亚哥","芝加哥","其它"],
},
{
"country":"加拿大",
"city":["温哥华","多伦多","蒙特利尔","其它"]
},
{
"country":"澳大利亚",
"city":["悉尼","墨尔本","其它"]
},
{
"country":"新加坡",
"city":["新加坡"]
},
]
},
methods:{
change_select(){
console.log("---------")
var that = this
that.cityName = ''
for(var k in that.area){
console.log(k)
console.log(that.area[k].country)
console.log(that.countryName)
if(this.countryName == that.area[k].country){
that.cityNames = that.area[k].city
console.log(that.cityNames)
}
}
}
}
})
</script>
</body>
</html>
<select>标签中v-model绑定的值要与标签<option>选中的值相等,则必须给<option>设置属性 v-bind:value="item.country" (给option选项设置一个值)否则无法select选中的值要么为空,要么是整个area列表中的值或者其中的某个json对象。area可以看成原始数据。
countryName:"",
cityName:"",
cityNames:[],
只是变量用来存储数据的。cityNames:[],是动态的获取城市列表的中间变量而已。
思路:
1、先遍历area;
2、判断当前遍历的area中的country是否与select标签选中的值countryName相等;
3、如果相等,则将当前国家中的city(城市)列表赋值给cityNames;
4、城市下拉框中option会遍历cityNames列表,vue动态的生成下拉框选项。