Vue.js 三级联动

先上代码,后面有说明

  • html

                                





  • js
var vm = new Vue({
    el: '#orderInfo',
    data: {
        orderInfo: {
            consignee: '',
            idCard: '',
            province: '',
            provinceCode: '',
            city: '',
            cityCode: '',
            dealerCode: '',
            dealerName: ''
        },
        selectedDealer: {code: -1},
        selectedProvince: {code: -1},
        selectedCity: {code: -1},
        provinceList: [],
        cityList: [],
        dealerList: []

    },
    methods: {
        submitOrder: function () {
            var _self = this;
            _self.orderInfo.provinceCode = _self.selectedProvince.code;
            _self.orderInfo.province = _self.selectedProvince.name;
            _self.orderInfo.cityCode = _self.selectedCity.code;
            _self.orderInfo.city = _self.selectedCity.name;
            _self.orderInfo.dealerCode = _self.selectedDealer.code;
            _self.orderInfo.dealerName = _self.selectedDealer.name;
            this.$http.post("/v1/api/order", _self.orderInfo).then(function (res) {
                alert(res.body.message);
                if (res.body.success) {
                    location.href = '/pay/index?orderSn=' + res.body.data.orderSn;
                }
            }, this.httpError);
        }
    },
    watch: {
        selectedProvince: function (newVal, oldVal) {
            var _self = this;
            if (newVal && typeof newVal != "undefined") {
                $.get("/v1/api/dealer/city/" + newVal.code, function (data) {
                    _self.cityList = data;
                    _self.selectedCity = {code: -1};
                });
            }
        },
        selectedCity: function (newVal, oldVal) {
            var _self = this;
            if (newVal && typeof newVal != "undefined" && newVal.code != -1) {
                $.get("/v1/api/dealer/" + newVal.code + "?level=" + newVal.level, function (data) {
                    _self.dealerList = data;
                })
            }
            _self.selectedDealer = {code: -1};
        }
    },

    created: function () {
        var _self = this;
        $.ajax({
            url: '/v1/api/dealer/province',
            type: "GET",
            dataType: 'json',
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (res) {
                _self.provinceList = res;
            }
        });
    }
})

以上是省,市,经销商的三级联动

注意点主要:

  • create方法中的ajax调用是同步方法,异步调用页面加载后省的数据可能还没请求回来
  • $.get(),$.post()方式调用接口要引用vue-resource.js
  • v-model 会忽略所有表单元素的 value、checked、selected 特性的初始值而总是将 Vue 实例的数据作为数据来源。你应该通过 JavaScript 在组件的 data 选项中声明初始值。
  • 如果 v-model 表达式的初始值未能匹配任何选项,