Vue+ajax实现三级联动

如何利用Vue实现三级联动,这里我们使用Vue组件实现,废话不多说,上干货
HTML


ajax.js
这里我利用原生js实现ajax调用(当复习了)

var proList = [];
var cityList = [];
var areaList = [];
createXmlHttpRequest();
//创建XMLHttpRequest
      function createXmlHttpRequest(){
          if(window.XMLHttpRequest){
              return new XMLHttpRequest();
          }else{
              return new ActiveXObject("Microsoft.XMLHTTP");
          }
      }
      var url="<%= request.getContextPath() %>/uploadServlet";
         //调用方法创建XMLHttpRequest对象
         XmlHttpRequest = createXmlHttpRequest();
         //设置回调函数
         XmlHttpRequest.onreadystatechange=finish;
         //初始化xmlhttprequest
         XmlHttpRequest.open("GET",url,true);
         //发送请求
         XmlHttpRequest.send(null);
         
         //ajax回调函数
         function finish(){
             if(XmlHttpRequest.readyState == 4&& XmlHttpRequest.status == 200){
                 var result = XmlHttpRequest.responseText;
                 //后台数据格式为数组嵌套对象
                 var json = eval("(" + result + ")");
                  proList = json[0];
                  cityList  = json[1];
                  areaList = json[2];
             }
         }
         module.export = {
       		 proList,
       		 cityList,
       		 areaList 
         }

index.js
这里一定要把Vue的基础记牢啊,template只能有一个根节点,这个错误我第一次做的时候就犯了

var ajaxPar = require('./ajax');
var proRows = ajaxPar.proList;
var cityRows = ajaxPar.cityList;
var areaRows = ajaxPar.areaList;
Vue.component('province',{
    template:'
\ \ \ \
', data: function () { return { proList: [], cityList: [], areaList: [], province: "", city: "", area: "", } }, created: function () { this.proList= proRows; this.province= this.proList.length > 0 ? this.proList[0].id : ""; var val = this.province; this.cityList= cityRows.filter(function (x) { return x.pid == val }); this.city= this.cityList.length > 0 ? this.cityList[0].id : ""; val = this.city; this.areaList= areaRows.filter(function(x){return x.pid == val}); this.area= this.areaList.length > 0 ? this.areaList[0].id : ""; }, watch: { unitSelected: function (val) { this.cityList= cityRows.filter(function (x) { return x.pid == val }); this.city= this.cityList.length > 0 ? this.cityList[0].id : ""; }, DepartmentSelected: function(val){ this.areaList= areaRows.filter(function(x){return x.pid == val}); this.area= this.areaList.length > 0 ? this.areaList[0].id : ""; } } }) new Vue({ el: "#proCity" })

如有错误还希望大家指正!

你可能感兴趣的:(前端Vue)