如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件

小編給大家分享一下如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

我們提供的服務(wù)有:網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站設(shè)計(jì)、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、鹽亭ssl等。為1000+企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的鹽亭網(wǎng)站制作公司

一、緣由

在項(xiàng)目開(kāi)發(fā)過(guò)程中,有一個(gè)需求是省市區(qū)地址選擇的功能,一開(kāi)始想的是直接使用靜態(tài)地址資源庫(kù)本地打包,但這種方式不方便維護(hù),于是放棄。后來(lái)又想直接讓后臺(tái)返回全部地址數(shù)據(jù),然后使用級(jí)聯(lián)選擇器進(jìn)行選擇,但發(fā)現(xiàn)數(shù)據(jù)傳輸量有點(diǎn)大且處理過(guò)程耗時(shí),于是又摒棄了這種方法。最后還是決定采用異步的方式進(jìn)行省市區(qū)地址選擇,即先查詢省份列表,然后根據(jù)選擇的省份code查詢城市列表,最后根據(jù)選擇的城市列表獲取區(qū)/縣列表,最終根據(jù)應(yīng)用場(chǎng)景不同,給出了兩種實(shí)現(xiàn)方案。

其中后臺(tái)總共需要提供4個(gè)接口,一個(gè)查詢所有省份的接口,一個(gè)根據(jù)省份code查詢其下所有城市的接口,一個(gè)根據(jù)城市code查詢其下所有區(qū)/縣的接口,以及一個(gè)根據(jù)地址code轉(zhuǎn)換成省市區(qū)三個(gè)code值的接口。

// 本人項(xiàng)目中使用的四個(gè)接口
`${this.API.province}/${countryCode}` // 根據(jù)國(guó)家code查詢省份列表,中國(guó)固定為156,可以拓展
`${this.API.city }/${provinceCode}` // 根據(jù)省份code查詢城市列表
`${this.API.area}/${cityCode}` // 根據(jù)城市code查詢區(qū)/縣列表
`${this.API.addressCode}/${addressCode}` // 地址code轉(zhuǎn)換為省市區(qū)code

二、基于el-cascader 級(jí)聯(lián)選擇器的單選擇框?qū)崿F(xiàn)方案

<template>
 <el-row>
  <el-cascader
   size="small"
   :options="city.options"
   :props="props"
   v-model="cityValue"
   @active-item-change="handleItemChange"
   @change="cityChange">
  </el-cascader>
 </el-row>
</template>

<script>
export default {
 name: 'addressSelector',
 props: {
  areaCode: null
 },

 model: {
  prop: 'areaCode',
  event: 'cityChange'
 },

 data () {
  return {
   // 所在省市
   city: {
    obj: {},
    options: []
   },
   props: { // 級(jí)聯(lián)選擇器的屬性配置
    value: 'value',
    children: 'cities',
    checkStrictly: true
   },
   cityValue: [], // 城市代碼
  }
 },
 computed: {
 },
 created () {
  this._initData()
 },
 mounted () {
 },
 methods: {
  _initData () {
   this.$http({
    method: 'get',
    url: this.API.province + '/156' // 中國(guó)
   }).then(res => {
    this.city.options = res.data.body.map(item => { // 所在省市
     return {
      value: item.provinceCode,
      label: item.provinceName,
      cities: []
     }
    })
   })
  },
  getCodeByAreaCode (code) {
   if (code == undefined) return false
   this.$http({
    method: 'get',
    url: this.API.addressCode + '/' + code
   })
   .then(res => {
    if (res.data.code === this.API.SUCCESS) {
     let provinceCode = res.data.body.provinceCode
     let cityCode = res.data.body.cityCode
     let areaCode = res.data.body.areaCode
     this.cityValue = [provinceCode, cityCode, areaCode]
     this.handleItemChange([provinceCode, cityCode])
    }
   })
   .finally(res => {
   })
  },
  handleItemChange (value) {
   let a = (item) => {
    this.$http({
     method: 'get',
     url: this.API.city + '/' + value[0],
    }).then(res => {
     item.cities = res.data.body.map(ite => {
      return {
       value: ite.cityCode,
       label: ite.cityName,
       cities: []
      }
     })
     if(value.length === 2){ // 如果傳入的value.length===2 && 先執(zhí)行的a(),說(shuō)明是傳入了areaCode,需要初始化多選框
      b(item)
     }
    }).finally(_ => {
    })
   }
   let b = (item) => {
    if (value.length === 2) {
     item.cities.find(ite => {
      if (ite.value === value[1]) {
       if (!ite.cities.length) {
        this.$http({
         method: 'get',
         url: this.API.area + '/' + value[1]
        }).then(res => {
         ite.cities = res.data.body.map(ite => {
          return {
           value: ite.areaCode,
           label: ite.areaName,
          }
         })
        }).finally(_ => {
        })
       }
      }
     })
    }
   }
   this.city.options.find(item => {
    if (item.value === value[0]) {
     if (item.cities.length) {
      b(item)
     } else {
      a(item)
     }
     return true
    }
   })
  },
  getCityCode () {
   return this.cityValue[2]
  },
  reset () {
   this.cityValue = []
  },
  cityChange (value) {
   if (value.length === 3) {
    this.$emit('cityChange', value[2])
   } else {
    this.$emit('cityChange', null)
   }
  }
 },
 watch: {
  areaCode: {
   deep: true,
   immediate: true,
   handler (newVal) {
    if (newVal) {
     this.getCodeByAreaCode(newVal)
    } else {
     this.$nextTick(() => {
      this.reset()
     })
    }
   }
  }
 }
}
</script>

<style lang="less" scoped>
</style>

最終效果如下(動(dòng)圖):

如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件

截圖:

如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件

三、基于el-select選擇器的多選擇框?qū)崿F(xiàn)方案

lt;template>
 <div id="addressHorizontalSelect">
  <el-row>
   <el-col
    :span="span">
    <el-select
     size="small"
     v-model="provinceCode"
     @focus="getProvinces"
     @change="changeProvince"
     :placeholder="$t('省')"
     filterable>
     <el-option
      v-for="item in provinceList"
      :key="item.provinceCode"
      :label="item.provinceName"
      :value="item.provinceCode">
     </el-option>
    </el-select>
   </el-col>
   <el-col
    :span="span"
    v-if="!hideCity">
    <el-select
     size="small"
     v-model="cityCode"
     @focus="getCities"
     @change="changeCity"
     :placeholder="$t('市')"
     filterable>
     <el-option
      v-for="item in cityList"
      :key="item.cityCode"
      :label="item.cityName"
      :value="item.cityCode">
     </el-option>
    </el-select>
   </el-col>
   <el-col
    :span="span"
    v-if="!hideCity && !hideArea">
    <el-select
     size="small"
     v-model="areaCode"
     @focus="getAreas"
     @change="changeArea"
     :placeholder="$t('區(qū)/縣')"
     filterable>
     <el-option
      v-for="item in areaList"
      :key="item.areaCode"
      :label="item.areaName"
      :value="item.areaCode">
     </el-option>
    </el-select>
   </el-col>
  </el-row>
 </div>
</template>

<script>
export default {
 name: 'addressHorizontalSelect',

 components: {},

 props: {
  hideCity: { // 隱藏市
   type: Boolean,
   default: false
  },
  hideArea: { // 隱藏區(qū)/縣
   type: Boolean,
   default: false
  },
  addressCode: null // 地址編碼
 },

 model: {
  prop: 'addressCode',
  event: 'addressSelect'
 },

 data() {
  return {
   provinceList: [], // 省份列表
   cityList: [], // 城市列表
   areaList: [], // 區(qū)/縣列表
   provinceCode: '', // 省份編碼
   cityCode: '', // 城市編碼
   areaCode: '', // 區(qū)/縣編碼
   cityFlag: false, // 避免重復(fù)請(qǐng)求的標(biāo)志
   provinceFlag: false,
   areaFlag: false
  }
 },

 computed: {
  span () {
   if (this.hideCity) {
    return 24
   }
   if (this.hideArea) {
    return 12
   }
   return 8
  }
 },

 watch: {
 },

 created () {
  this.getProvinces()
 },

 methods: {
  /**
   * 獲取數(shù)據(jù)
   * @param {Array} array 列表
   * @param {String} url 請(qǐng)求url
   * @param {String} code 編碼(上一級(jí)編碼)
   */
  fetchData (array, url, code) {
   this.$http({
    method: 'get',
    url: url + '/' + code
   })
   .then(res => {
    if (res.data.code === this.API.SUCCESS) {
     let body = res.data.body || []
     array.splice(0, array.length, ...body)
    }
   })
   .catch(err => {
    console.log(err)
   })
   .finally(res => {
   })
  },
  // 根據(jù)國(guó)家編碼獲取省份列表
  getProvinces () {
   if (this.provinceFlag) {
    return
   }
   this.fetchData(this.provinceList, this.API.province, 156)
   this.provinceFlag = true
  },
  // 省份修改,拉取對(duì)應(yīng)城市列表
  changeProvince (val) {
   this.fetchData(this.cityList, this.API.city, this.provinceCode)
   this.cityFlag = true
   this.cityCode = ''
   this.areaCode = ''
   this.$emit('addressSelect', val)
  },
  // 根據(jù)省份編碼獲取城市列表
  getCities () {
   if (this.cityFlag) {
    return
   }
   if (this.provinceCode) {
    this.fetchData(this.cityList, this.API.city, this.provinceCode)
    this.cityFlag = true
   }
  },
  // 城市修改,拉取對(duì)應(yīng)區(qū)域列表
  changeCity (val) {
   this.fetchData(this.areaList, this.API.area, this.cityCode)
   this.areaFlag = true
   this.areaCode = ''
   this.$emit('addressSelect', val)
  },
  // 根據(jù)城市編碼獲取區(qū)域列表
  getAreas () {
   if (this.areaFlag) {
    return
   }
   if (this.cityCode) {
    this.fetchData(this.areaList, this.API.area, this.cityCode)
   }
  },
  // 區(qū)域修改
  changeArea (val) {
   this.$emit('addressSelect', val)
  },
  // 重置省市區(qū)/縣編碼
  reset () {
   this.provinceCode = '',
   this.cityCode = '',
   this.areaCode = ''
  },
  // 地址編碼轉(zhuǎn)換成省市區(qū)列表
  addressCodeToList (addressCode) {
   if (!addressCode) return false
   this.$http({
    method: 'get',
    url: this.API.addressCode + '/' + addressCode
   })
   .then(res => {
    let data = res.data.body
    if (!data) return
    if (data.provinceCode) {
     this.provinceCode = data.provinceCode
     this.fetchData(this.cityList, this.API.city, this.provinceCode)
    } else if (data.cityCode) {
     this.cityCode = data.cityCode
     this.fetchData(this.areaList, this.API.area, this.cityCode)
    } else if (data.areaCode) {
     this.areaCode = data.areaCode
    }
   })
   .finally(res => {
   })
  }
 },

 watch: {
  addressCode: {
   deep: true,
   immediate: true,
   handler (newVal) {
    if (newVal) {
     this.addressCodeToList(newVal)
    } else {
     this.$nextTick(() => {
      this.reset()
     })
    }
   }
  }
 }
}
</script>

<style lang="less" scoped>
</style>

實(shí)現(xiàn)效果如下(動(dòng)圖):

如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件

以上是“如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

名稱欄目:如何實(shí)現(xiàn)基于Vue+ElementUI的省市區(qū)地址選擇通用組件
瀏覽路徑:http://www.muchs.cn/article24/phohje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、面包屑導(dǎo)航、標(biāo)簽優(yōu)化、企業(yè)網(wǎng)站制作、網(wǎng)站策劃、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)