← 返回首页
Vue基础教程(十八)
发表时间:2020-11-06 18:00:09
监听器综合案例

使用监听器实现一个省市级联效果。

代码如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title></title>
    <!--我们使用的是CDN资源,在线获取,必须保证能上网-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--这段代码千篇一律,几乎每个vue页面都会有这么一段代码,程序员比较懒,不愿意每次都要写。怎么办?代码模板-->
<div id="app">
    <!--每次都会默认把当前事件对象当成方法的第一个参数传过去-->
    省份:<select id="province" v-model="currentSelectedProvince">
    <option v-for="(p,index) in provinces" :key="index" :value="p.name">{{p.name}}</option>
</select>

    <!--value单向绑定,v-model双向绑定-->
    城市:<select v-model="currentSelectedCity">
    <option v-for="(c,index) in currentSelectedCitys" :key="index" :value="c">{{c}}</option>
</select>

    <input type="button" value="显示籍贯" @click="showNation"/>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        //属性
        data: {
            currentSelectedProvince: '', //当前选中的省份
            currentSelectedCity: '', //当前选中的城市,
            currentSelectedCitys: [],//当前城市的集合,
            provinces: [
                {
                    name: '----请选择----',
                    citys: ['']
                },
                {
                    name: '河北',
                    citys: ['石家庄', '唐山', '秦皇岛', '邯郸']
                },
                {
                    name: '河南',
                    citys: ['郑州', '开封', '洛阳', '安阳']
                },
                {
                    name: '山东',
                    citys: ['济南', '青岛', '烟台', '潍坊']
                },
                {
                    name: '山西',
                    citys: ['太原', '大同', '运城', '临汾']
                }
            ]
        },
        //计算器
        computed: {},
        //监视器
        watch: {
            //监听currentSelectedProvince属性的改变
            currentSelectedProvince(newValue, oldValue) {
                //遍历省份的集合
                for (let i = 0; i < this.provinces.length; i++) {
                    if (this.provinces[i].name == newValue) {
                        this.currentSelectedCitys = this.provinces[i].citys;
                        break; //跳出循环.
                    }
                }
                this.currentSelectedCity = this.currentSelectedCitys[0];
            }
        },
        //挂载
        mounted() {
            this.currentSelectedProvince = this.provinces[0].name;
            this.currentSelectedCity = this.provinces[0].citys[0];
        },
        //加载
        created() {

        },
        //事件
        methods: {
            showNation: function () {
                //这里打印用户选择的籍贯,省份+城市
                console.log(this.currentSelectedProvince + "," + this.currentSelectedCity);
            }
        }
    });
</script>
</body>
</html>

运行效果如下: