SpringBoot + Element 省 市 县/区 三级联动

熊孩纸 阅读:687 2021-03-31 13:44:48 评论:0

效果展示:

实现思路: 

1、下拉框绑定自定义实体参数对象,下拉框选项动态绑定自定义数组对象:

省:

<el-select v-model="provinceAreaCode" placeholder="请选择" @change="getCityList"> 
            <el-option 
                v-for="(item,index) in provinceList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode"> 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select>

市:

 <el-select v-model="cityAreaCode" placeholder="请选择" @change="getAreaList"> 
            <el-option 
                v-for="(item,index) in cityList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode" 
            > 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select>

区/县:

<el-select v-model="streetAreaCode" placeholder="请选择"> 
            <el-option 
                v-for="(item,index) in areaList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode" 
            > 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select>

2、VUE实例化对象中定义自定义参数实体对象,下拉框选项动态绑定自定义数组对象:

data() { 
    return { 
       loading: true, 
        // 省list 
        provinceList: [], 
         // 省code 
        provinceAreaCode: this.province, 
         // 市list 
        cityList: [], 
        // 市code 
        cityAreaCode: this.city, 
        // 区list 
        areaList: [], 
        // 区code 
        streetAreaCode: this.myArea 
    } 
  }

3、VUE 实例方法定义定义获取下拉框选项的后台接口,并在vue 实例化时完成接口后端调用

4、$emit:子传父

     props:父传子

 

相关代码:

VUE +ElementUI 源码:

 
 <style> 
</style> 
<template> 
     <section> 
         <el-select v-model="provinceAreaCode" placeholder="请选择" @change="getCityList"> 
            <el-option 
                v-for="(item,index) in provinceList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode"> 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select> 
         <el-select v-model="cityAreaCode" placeholder="请选择" @change="getAreaList"> 
            <el-option 
                v-for="(item,index) in cityList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode" 
            > 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select> 
         <el-select v-model="streetAreaCode" placeholder="请选择"> 
            <el-option 
                v-for="(item,index) in areaList" 
                :key="index" 
                :label="item.areaName" 
                :value="item.areaCode" 
            > 
                {
  
   { item.areaName }} 
            </el-option> 
        </el-select> 
 
     </section> 
</template> 
 
<script> 
export default { 
  name: 'User', 
  props:{ 
    /** 
    * 省 
    */ 
    province: { 
      type: String, 
      required: false, 
      default: () => null 
    }, 
    /** 
    * 市 
    */ 
    city: { 
      type: String, 
      required: false, 
      default: () => null 
    }, 
    /** 
     *  区 
    */ 
    myArea: { 
      type: String, 
      required: false, 
      default: () => null 
    } 
   }, 
  data() { 
    return { 
       loading: true, 
        // 省list 
        provinceList: [], 
         // 省code 
        provinceAreaCode: this.province, 
         // 市list 
        cityList: [], 
        // 市code 
        cityAreaCode: this.city, 
        // 区list 
        areaList: [], 
        // 区code 
        streetAreaCode: this.myArea 
    } 
  }, 
  watch:{ 
     /** 
     * 监听省code 
     * @param val 
      */ 
      provinceAreaCode(val) { 
        console.log("provinceAreaCode" + val); 
        this.$emit('update:province', val) 
      }, 
       /** 
       * 监听省 
       * @param val 
       */ 
       province(val) { 
         console.log("province" + val); 
          this.provinceAreaCode = val 
          if (val) { 
              this.getCityList(val) 
          } 
      }, 
      /** 
      * 监听市code 
      * @param val 
      */ 
      cityAreaCode(val) { 
        console.log("cityAreaCode" + val); 
        this.$emit('update:city', val) 
      }, 
 
      /** 
      * 监听市 
      * @param val 
      */ 
      city(val) { 
        console.log("city" + val); 
        this.cityAreaCode = val 
        if (val) { 
           this.getAreaList(val) 
        } 
      }, 
      /** 
       * 监听区code 
       * @param val 
       */ 
      streetAreaCode(val) { 
        console.log("streetAreaCode" + val); 
        this.$emit('update:myArea', val) 
      }, 
      /** 
      * 监听区 
      * @param val 
      */ 
      myArea(val) { 
        console.log("myArea" + val); 
        this.streetAreaCode = val 
      } 
  }, 
   methods: { 
       /** 
        * 获取省 
        */ 
        getProvince() { 
          var self = this 
          this.$axios.get('/location/find') 
          .then(function (res) { 
            self.provinceList = []; 
            res.data.data.forEach(item => { 
                let arr = { 
                    areaName: item.name, 
                    areaCode: item.code 
                }; 
                self.provinceList.push(arr); 
            }); 
          }) 
          .catch(function (err) { 
            console.log(err) 
          }) 
        }, 
         /** 
        * 获取市 
        * @param id 
        */ 
        getCityList(id) { 
          var self = this 
          this.$axios.get('/location/city?areaCode=' + id) 
          .then(function (res) { 
            self.cityList = []; 
            res.data.data.forEach(item => { 
                let arr = { 
                    areaName: item.name, 
                    areaCode: item.code 
                }; 
                self.cityList.push(arr); 
            }); 
          }) 
          .catch(function (err) { 
            console.log(err) 
          }) 
        }, 
        /** 
        * 获取地区 
        * @param id 
        */ 
        getAreaList(id) { 
          var self = this 
          this.$axios.get('/location/area?areaCode=' + id) 
          .then(function (res) { 
            self.areaList = []; 
            res.data.data.forEach(item => { 
                let arr = { 
                    areaName: item.name, 
                    areaCode: item.code 
                }; 
                self.areaList.push(arr); 
            }); 
          }) 
          .catch(function (err) { 
            console.log(err) 
          }) 
        } 
 
   }, 
   mounted() { 
     this.getProvince() 
   } 
 
} 
</script>

SpringBoot 后端代码:

package com.zzg.controller; 
 
import java.io.File; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.regex.Pattern; 
import java.util.stream.Collectors; 
 
import org.apache.commons.io.FileUtils; 
import org.apache.commons.lang3.StringUtils; 
import org.springframework.stereotype.Controller; 
import org.springframework.util.ResourceUtils; 
import org.springframework.web.bind.annotation.CrossOrigin; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.ResponseBody; 
 
import com.alibaba.fastjson.JSONArray; 
import com.alibaba.fastjson.JSONObject; 
 
import io.swagger.annotations.Api; 
import io.swagger.annotations.ApiOperation; 
 
@Controller 
@RequestMapping("/api/location") 
@CrossOrigin 
@Api(value = "模拟测试Controlle", tags = "模拟测试操作服务") 
public class TestLocation { 
	static JSONArray array = null; 
	static { 
		try { 
			String path = ResourceUtils.getURL("classpath:data.json").getPath(); 
			File file = new File(path); 
			if(file.exists()) { 
				String content = FileUtils.readFileToString(file,"UTF-8"); 
				if(StringUtils.isNotEmpty(content)) { 
					array = JSONArray.parseArray(content); 
				} 
			} 
		} catch (Exception e) { 
			// TODO Auto-generated catch block 
			System.out.println(e.getMessage()); 
		} 
	} 
	 
	@RequestMapping(value="/find", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "GET", value = "模拟测试对象查询") 
	public String find() { 
		List<JSONObject> list = null; 
		if(array != null) { 
			list = array.stream().filter(item ->{ 
				JSONObject object = (JSONObject)item; 
				String code = object.getString("code"); 
				return Pattern.matches("^[\\s\\S]*0000$", code); 
			}).map(item ->{ 
				return (JSONObject)item; 
			}).collect(Collectors.toList()); 
		} 
 
		 
		JSONObject obj = new JSONObject(); 
		obj.put("code", 0); 
		obj.put("data", list); 
		return obj.toJSONString(); 
	} 
	 
	@RequestMapping(value="/city", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "GET", value = "模拟测试对象查询") 
	public String city(@RequestParam(required = false) String areaCode) { 
		// 省编码: 
		System.out.println("省编码:" + areaCode.substring(0, 1)); 
		List<JSONObject> list = null; 
		if(array != null) { 
			list = array.stream().filter(item ->{ 
				JSONObject object = (JSONObject)item; 
				String province = object.getString("province"); 
				String code = object.getString("code"); 
				Object obj = object.get("area"); 
				 
				boolean target = true; 
				if(obj instanceof String) { 
					target = false; 
				} 
				return province.equalsIgnoreCase(areaCode.substring(0, 2)) && !Pattern.matches("^[\\s\\S]*0000$", code) && target; 
			}).map(item ->{ 
				return (JSONObject)item; 
			}).collect(Collectors.toList()); 
		} 
 
		 
		JSONObject obj = new JSONObject(); 
		obj.put("code", 0); 
		obj.put("data", list); 
		return obj.toJSONString(); 
	} 
	 
	@RequestMapping(value="/area", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8") 
	@ResponseBody 
	@ApiOperation(httpMethod = "GET", value = "模拟测试对象查询") 
	public String area(@RequestParam(required = false) String areaCode) { 
		// 省编码: 
		System.out.println("省编码:" + areaCode.substring(0, 2)); 
		System.out.println("市编码:" + areaCode.substring(2, 4)); 
		List<JSONObject> list = null; 
		if(array != null) { 
			list = array.stream().filter(item ->{ 
				JSONObject object = (JSONObject)item; 
				// 省编码 
				String province = object.getString("province"); 
				// 唯一编码 
				String code = object.getString("code"); 
				// 市编码 
				String city = object.getString("city"); 
				// 区域编码 
				Object area = object.get("area"); 
				boolean target = true; 
				if(area instanceof Integer) { 
					target = false; 
				} 
				return province.equalsIgnoreCase(areaCode.substring(0, 2)) && city.equalsIgnoreCase(areaCode.substring(2, 4)) && !Pattern.matches("^[\\s\\S]*0000$", code) && target; 
			}).map(item ->{ 
				return (JSONObject)item; 
			}).collect(Collectors.toList()); 
		} 
 
		 
		JSONObject obj = new JSONObject(); 
		obj.put("code", 0); 
		obj.put("data", list); 
		return obj.toJSONString(); 
	} 
 
 
} 

 

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号