基于Ant Design Vue的省市區(qū)級(jí)聯(lián)選擇組件應(yīng)用

對(duì)于省市區(qū)級(jí)聯(lián)選擇,很多做法都是通過一級(jí)一級(jí)的調(diào)用服務(wù)端接口來實(shí)現(xiàn)的,今天介紹一個(gè)完全采用前端、基于Ant Design Vue來構(gòu)建的省市區(qū)級(jí)聯(lián)選擇組件。

一、準(zhǔn)備省市區(qū)數(shù)據(jù)

1.下載省市區(qū)數(shù)據(jù)
省市區(qū)JSON數(shù)據(jù)

2.將省市區(qū)數(shù)據(jù)保存到areadata.js文件中,并導(dǎo)出

//地區(qū)json數(shù)據(jù)
export default [
    {
        code: "11",
        name: "北京市",
        children: [
            {
                code: "1101",
                name: "市轄區(qū)",
                children: [
                    {
                        code: "110101",
                        name: "東城區(qū)"
                    },
                    {
                        code: "110102",
                        name: "西城區(qū)"
...

二、基于Cascader包裝成省市區(qū)組件

<template>
  <a-cascader
    :fieldNames="{ label: 'name', value: 'code', children: 'children' }"
    :options="areaData"
    :placeholder="placeholder"
    v-model="selectedValues"
    @change="onChange"
  />
</template>
<script>
import areaData from "./areadata";
export default {
  name: "areaSelect",
  props: {
    placeholder: {
      type: String,
      default: "請(qǐng)選擇省市區(qū)",
    },
    defaultValue: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      //地區(qū)數(shù)據(jù)
      areaData,
      //選擇的數(shù)據(jù)
      selectedValues: [],
    };
  },
  created() {
    if (this.defaultValue.length) {
      this.selectedValues = [...this.defaultValue];
    }
  },
  watch: {
    defaultValue(newValue) {
      if (newValue.length) {
        this.selectedValues = newValue;
      } else {
        this.selectedValues = [];
      }
    },
  },
  methods: {
    //選擇好之后的回調(diào)
    onChange(value) {
      this.$emit("change", value);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

三、使用該組件

<template>
  <div>
    <!-- 省市區(qū)選擇器 -->
    <area-select
      @change="selectArea"
      :default-value="defaultArea"
    />
  </div>
</template>
<script>
//導(dǎo)入構(gòu)建好的組件
import areaSelect from "./areaselect";
export default {
  components: {
    areaSelect,
  },
  data() {
    return {
      //配置默認(rèn)選中的省市區(qū)(依次是省市區(qū)的區(qū)域代碼)
      defaultArea:['32','3205','320571'],
    };
  },
  methods: {
    //選擇地區(qū)之后的回調(diào)
    selectArea(selectedArea) {
      console.log(selectedArea);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

四、效果

效果1
效果2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容