我们拿,省,市,区,来举例做一个简单的Vue三级联动下拉菜单
首先填入测试数据
数据层:
public List<City> GetCity(int Pid) { return db.City.Where(w => w.ParentId == Pid).ToList(); }
Pid为自定义变量
控制器:
[HttpGet] public ActionResult GetCity(int Pid) { return Json(dal.GetCity(Pid), JsonRequestBehavior.AllowGet); }
控制器与单一下拉菜单并无区别
<tr> <td>籍贯</td> <td colspan="3"> <select v-model="FormData.ProvinceId" v-on:change="getCity"> <option v-for="a in provinceItem" :value="a.CId">{{a.CName}}</option> </select>- <select v-model="FormData.CityId" v-on:change="getCounty"> <option v-for="a in cityItem" :value="a.CId">{{a.CName}}</option> </select>- <select v-model="FormData.CountyId"> <option v-for="a in countyItem" :value="a.CId">{{a.CName}}</option> </select> </td> </tr>
注意:一级与二级利用V-on:change事件来出发各自下一级方法
下面是具体的Vue语法:
let app = new Vue({ el: "#app", data() { return { FormData: { ProvinceId: "0", CityId: "0", CountyId: "0", }, selectItem: [],//部门 provinceItem: [],//省 cityItem: [],//市 countyItem: []//区 }; }, methods: { //加载部门 //省 getProvince() { axios.get('/Employee/GetCity?pid=0').then(res => { this.provinceItem = res.data; this.provinceItem.unshift({ "CId": "0", "CName": "请选择" }) }) }, //市 getCity() { this.cityItem = []; this.countyItem = []; axios.get('/Employee/GetCity?pid=' + this.FormData.ProvinceId).then(res => { this.cityItem = res.data; this.cityItem.unshift({ "CId": "0", "CName": "请选择" }); this.formData.CityId = this.cityItem[0].CId; }) }, //区 getCounty() { this.countyItem = []; axios.get('/Employee/GetCity?pid=' + this.FormData.CityId).then(res => { this.countyItem = res.data; this.countyItem.unshift({ "CId": "0", "CName": "请选择" }); this.formData.CountyId = this.countyItem[0].CId; }) }, }, created: function () { this.getDept(); this.getProvince(); } })