我們拿,省,市,區,來舉例做一個簡單的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(); } })