vue:watch()事件侦听
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/vue.js" type="text/javascript"></script>
<style type="text/css">
select {
width: 75px;
}
</style>
</head>
<body>
<div id="jilian">
<select v-model="p">
<option v-for="prov in pList" v-bind:value="prov">{{prov}}</option>
</select>
<select v-model="c">
<option v-for="city in cList" v-bind:value="city">{{city}}</option>
</select>
<select v-model="d">
<option v-for="dist in dList" v-bind:value="dist">{{dist}}</option>
</select>
</div>
<script>
new Vue({
el: "#jilian",
data: {
p: "",
pList: ["湖北省", "浙江省"],
c: "",
cList: [],
d: "",
dList: []
},
// 这里侦听的内容为data里进行数据绑定的内容【这里有p,c,d】,名称需要一致,侦听内容需要修改可以定义方法来对侦听到的内容进行修改
watch: {
// 对p侦听
p() {
if (this.p == "湖北省") {
this.cList = ["武汉市", "黄冈市"]
this.c = this.cList[0]
} else if (this.p == "浙江省") {
this.cList = ["杭州市", "金华市"]
this.c = this.cList[0]
}
},
// 对c侦听,并且根据侦听到的内容相应做出变化
c() {
if (this.c == "武汉市") {
this.dList = ["江汉区", "江夏区", "洪山区"]
this.d = this.dList[0]
} else if (this.c == "黄冈市") {
this.dList = ["黄冈1区", "黄冈2区", "黄冈1区"]
this.d = this.dList[0]
} else if (this.c == "杭州市") {
this.dList = ["西湖区", "钱塘区", "上城区"]
this.d = this.dList[0]
} else if (this.c == "金华市") {
this.dList = ["金华1区", "金华2区", "金华3区"]
this.d = this.dList[0]
}
}
}
});
</script>
</body>
</html>
得到效果: