vue 省市县三级联动

1、

<template>
  <div>
    所在省
    <el-select popper-class="eloption" :popper-append-to-body="true"
      @change="getShiList(obj.province)" v-model="obj.province" placeholder="请选择所在省" clearable
      @clear="removeSheng()">
      <el-option v-for="(item, index) in shengList" :key="item.code" :value="item.name" :label="item.name" />
    el-select>
    所在市
    <el-select popper-class="eloption" :popper-append-to-body="true"
      @change="getAreaList(obj.city)" v-model="obj.city" placeholder="请选择所在市" clearable @clear="removeShi()">
      <el-option v-for="(item, index) in shiList" :key="item.code" :value="item.name" :label="item.name" />
    el-select>
    所在区
    <el-select popper-class="eloption" :popper-append-to-body="true" @change="$forceUpdate()"
      v-model="obj.area" placeholder="请选择所在区" clearable>
      <el-option v-for="(item, index) in areaList" :key="item.code" :value="item.name" :label="item.name" />
    el-select>
  div>
template>

<script>
const arr = require('@/assets/city.js');
export default {
  data() {
    return {
      shengList: arr.default,
      shiList: [],  //arr.default[0].code  北京市一个对象,其他省可有多个市
      areaList: [],
      obj: {
        // province:'',
        // city: '',
        // area: '',
      },

    }
  },
  methods:{
    // 获得市
    getShiList(shengName) {
      this.$forceUpdate()
      this.obj.city = ''
      this.obj.area = ''
      this.shengList.forEach(v => {
        if (v.name == shengName) {
          this.shiList = v.children
        }
      })
    },
    // 获得区
    getAreaList(shiName) {
      this.$forceUpdate()
      this.obj.area = ''
      this.shiList.forEach(v => {
        if (v.name == shiName) {
          this.areaList = v.children
        }
      })
    },
    removeSheng(e){
      console.log("删除省")
      this.$forceUpdate()
      // this.obj.sheng = ''
      // this.obj.city = ''
      // this.obj.area = ''
      this.shiList = []
      this.areaList = []
    },
    removeShi(e){
      console.log("删除shi")
      this.$forceUpdate()
      // this.obj.city = ''
      // this.obj.area = ''
      this.areaList = []
    },
  }
}
script>

<style>style>

2、city.js
文件太大了(0积分,免费下载)
https://download.csdn.net/download/Ann_52547/87755408
格式是这样的:

const arr = [
{
    "code": "11",
    "name": "北京市",
    "children": [{
      "code": "1101",
      "name": "北京市",
      "children": [
      	{
          "code": "110101",
          "name": "东城区"
        },
        {
          "code": "110102",
          "name": "西城区"
        }]
    }]
 }

参考:
1、这个文件可以下载
省市区三级联动城市数据js文件。(复制后放入citys.js文件中,可自定义文件名)
2、distpicker插件编写
vue实现省市县三级联动,超简单
3、vue中实现省市区三级联动(V-Distpicker插件)

你可能感兴趣的:(vue.js,javascript,前端)