vue+element省市縣的二級聯動功能

項目中有選擇省市縣的需求,先選擇省,再選擇縣ios

解決這個需求也不是很難,整體思路就是看後端接口,axios

通常後端接口都是請求參數爲 0 返回省的數據,不爲 0 的話返回相對應的市的數據後端

 

template代碼:數組

 1 <el-form-item label="所屬地區: ">
 2           <el-select
 3             v-model="form.province"
 4             @change="getRegion(form.province)"
 5             placeholder="請選擇省份"
 6             style="width: 165px;"
 7           >
 8             <el-option
 9               :label="item1.region_name"
10               :value="item1.region_id"
11               v-for="(item1,i) in provinceList"
12               :key="i"
13             ></el-option>
14           </el-select>
15           <el-select
16             v-model="form.city"
17             placeholder="請選擇城市"
18             style="width: 165px;margin-left:10px;"
19           >
20             <el-option
21               v-for="(item2,i) in cityList"
22               :key="i"
23               :label="item2.region_name"
24               :value="item2.region_id"
25             ></el-option>
26           </el-select>
27         </el-form-item>

script代碼:async

data數據聲明:post

 1  data() {
 2     return {
 3       form: {
 4         province: "",
 5         city: "",
 6       },
 7       // 省市縣的信息
 8       provinceList: [], //獲取的一級數組數據
 9       cityList: [] //獲取的二級數組數據
10     };
11   },

 

經過判斷  region_id 來發請求獲取數據this

methods代碼:spa

 1 async getRegion(id) {
 2       let _this = this;
 3       let data = {
 4         region_id: id
 5       };
 6       this.form.city = "";
 7       if (id == 0) {
 8         const res = await this.$axios.post("/region/list", { ...data });
 9         _this.provinceList = res.data;
10       } else {
11         const res = await this.$axios.post("/region/list", { ...data });
12         _this.cityList = res.data;
13       }
14     },
相關文章
相關標籤/搜索