Vue realizes cascading selection of provinces, cities and districts

Vue realizes cascading selection of provinces, cities and districts

Recently, I need to implement a cascading selection effect for provinces, cities and districts. The data for provinces, cities and districts all use local data, and the logic for implementation is a bit complicated. I will list the summary of the PC side here to share. The code for the mobile side is similar. Except for HTML, the rest can be copied and used according to needs. I hope this helps you all.

1. Rendering

PC side effect picture:

Mobile terminal effect diagram:

2. Implementation Logic

My implementation logic here is to first obtain the city through the province, and then obtain the district and county through the city. Since the street is not fixed, let the user enter it by himself. The logic for obtaining the corresponding urban area is: each province, city, district and county has a unique code, and the first two digits of the province code are the same as the city, so the city can be filtered out by interception, and the first four digits of the city code are the same as the district and county, so the district and county can also be filtered out by interception.

Because I used the select component of the element-ui framework to implement the PC side, the data structure of provinces, cities and districts is as follows:

The mobile terminal is implemented using the van-picker component of the vant framework. The data structure is different from that of the PC terminal, so the data structure of provinces, cities and districts is as follows:

3. Related Code

<!--PC code-->
 <el-form :inline="true" :model="addressForm">
        <el-form-item label="省" label-width="100px" prop="province">
          <el-select v-model="addressForm.province" placeholder="Please select" style="width:250px" @change="bindProvinceChange">
          <!-- :value="item.value+'|'+item.label" If you want to get both the number and the province name, the value assignment can be written like this, and then cut with |. If you don't need to get both, just assign one. -->
            <el-option v-for="item in provinceList" :label="item.label" :value="item.value+'|'+item.label"></el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item label="市" label-width="100px" prop="city">
          <el-select v-model="addressForm.city" placeholder="Please select" style="width:250px" @change="bindCityChange">
            <el-option v-for="item in cityList" :label="item.label" :value="item.value+'|'+item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="District/County" label-width="100px" prop="county">
          <el-select v-model="addressForm.county" placeholder="Please select" style="width:250px" @change="bindCountyChange">
            <el-option v-for="item in countyList" :label="item.label" :value="item.value+'|'+item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Street/Town" label-width="100px" prop="street">
          <el-input type="textarea" :rows="3" resize="none" placeholder="Please enter street information" v-model="addressForm.street"
            style="width:250px">
          </el-input>
        </el-form-item>
</el-form>

The code in this section is basically the same. The only difference is that the onchange event on the mobile terminal can directly obtain the unique number, and there is no need to cut it like on the PC side. You can modify it according to your needs.

var app = new Vue({
      el: '#app',
       data: {
    addressForm: {
           province: '',
           city: '',
           county: '',
           street: ''
         },
         // The data of provinces, cities and districts are placed in another file. I am importing the provinceList directly from another file: areaList.provinceList,
         cityList: [],
         countyList: []
  },
  methods:{
   // Province bindProvinceChange(vals) {
         // Get the unique number corresponding to the province console.log('data========>', vals)
           let arr = vals.split('|')
           this.addressForm.province = arr[1]
           this.addressForm.city = '';
           this.addressForm.county = '';
           this.addressForm.street = '';
           // Get the corresponding city this.cityList = this.addrInit(2, areaList.cityList, arr[0]);
         },
         // City bindCityChange(vals) {
           console.log('vals------->', vals)
           this.addressForm.county = '';
           this.addressForm.street = '';
           let arr = vals.split('|')
           this.addressForm.city = arr[1]
            // Get the corresponding district and county this.countyList = this.addrInit(4, areaList.countyList, arr[0]);
         },
         //District and county bindCountyChange(vals) {
           console.log('vals------======>', vals)
           this.addressForm.street = '';
           let arr = vals.split('|')
           this.addressForm.county = arr[1]
         },
         // Convert the object to an array transArray(obj) {
           let arr = [];
           for (let i in obj) {
             arr.push(obj[i]);
           }
           return arr;
         },
         /**
          * Encapsulation method - get the corresponding province, city, and district* @param {number} num The number of digits to be intercepted* @param {*} list The array to be queried* @param {*} str The string to be intercepted* @returns
          */
         addrInit(num, list, str) {
           let strSub = str.substr(0, num);
           let arr = this.transArray(list);
           let newArr = arr.filter(function (val, index, arr) {
             let newStr = val.value.substr(0, num);
             return newStr == strSub;
           });
           return newArr;
         },
  }
 })

I hope this helps you all! !

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • General component for selecting provincial, municipal and district addresses based on Vue+ElementUI
  • Vue implements mobile terminal province, city and district selection
  • Vue implements province, city and district selection on mobile phone
  • Vue.js imitates the selection component example code of Jingdong's three-level linkage of provinces, cities and districts
  • Implementation of Vue province, city and district three-link drop-down selection component

<<:  Summarize the common application problems of XHTML code

>>:  Docker+nextcloud to build a personal cloud storage system

Recommend

How to create a project with WeChat Mini Program using typescript

Create a project Create a project in WeChat Devel...

Solve the Linux Tensorflow2.0 installation problem

conda update conda pip install tf-nightly-gpu-2.0...

Navicat for MySQL scheduled database backup and data recovery details

Database modification or deletion operations may ...

Solution to MySQL root password error number 1045

Stop MySQL Service Windows can right-click My Com...

Detailed explanation of uniapp painless token refresh method

When the front-end requests the interface, it is ...

JS implements a simple counter

Use HTML CSS and JavaScript to implement a simple...

Simple usage example of MySQL 8.0 recursive query

Preface This article uses the new features of MyS...

Implementation steps of Mysql merge results and horizontal splicing fields

Preface Recently, I was working on a report funct...

Detailed tutorial on installing Python 3.6.6 from scratch on CentOS 7.5

ps: The environment is as the title Install possi...

Implementing Binary Search Tree in JavaScript

The search binary tree implementation in JavaScri...

This article will show you how to use Vue 3.0 responsive

Table of contents Use Cases Reactive API related ...