English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

WeChat Mini Program: Example Code of Provinces, Cities, and Counties Linkage Encapsulated by Picker

 WeChat Mini Program: Example of Province-City-District Three-Level联动 Encapsulation

  Currently, learning WeChat Mini Program is more about whether it can encapsulate other components twice, which is beneficial for rapid development of various WeChat Mini Programs in the future. Currently, it is found that the selector mode of picker only has one level dropdown, so can we go through}}3How to introduce the template form of a three-level联动 picker from other pages? The answer is definitely yes. So, my idea is like this:

1Using template template syntax for encapsulation, data is passed from the page

2According to the syntax of picker componentThe range can only be an array of Chinese regions, but we need a unique code for each region to trigger the next level联动 data. So, my approach is to store two arrays of data, one for Chinese names and the other for unique codes, in an object. Format 【province:{code:['110000', '"220000'...], name: ['Beijing City', 'Tianjin City'...]}], this format is fixed and requires the server to return in coordination

3Through the bindchange event of picker to obtain the data of the next level, each method is written into the function and exposed for page calls

Then let me talk about the directory structure of my demo:

common

    -net.js//wx.request interface secondary integration

    -cityTemplate.js//Three-level联动 method

page

    -demo

        -demo.js

        -demo.wxml

template

    -cityTemplate.wxml

app.js

app.json

app.wxss

Then, I set up a simple server using phpstudy for testing. Don't ask me why the server is like this, I don't know either, I'm just starting out and I just need the data...

Of course, you can skip this step and directly fix the data in demo.js for testing...

The code is as follows: [The return data format of the server follows the specification of the following retArr]

<?php 
header("Content-type: text/html; charset=utf-8);  
$type=$_REQUEST["type"];//Obtain the symbol of provinces, cities, and districts 
$fcode=$_GET["fcode"]; 
$retArr=[ 
  "status"=>true, 
  "data"=>[], 
  "msg"=>"" 
); 
if($type!="province" && $type!="city" && $type!="county"){ 
  $retArr["status"]=false; 
  $retArr["msg"]="Error retrieving region type, please check"; 
  echo json_encode($retArr); 
  exit; 
} 
function getProvince(){ 
  $province=[]; 
  $code=["110000", "350000", "710000"]; 
  $province["code"]=$code; 
  $name=["北京市", "福建省", "台湾省"]; 
  $province["name"]=$name; 
  $fcode=["0", "0", "0"]; 
  $province["fcode"]=$fcode; 
  return $province; 
} 
function getCity($P_fcode){ 
  $city=[]; 
  $code=[]; 
  $name=[]; 
  $fcode=[]; 
  if($P_fcode=="110000"){ 
    $code=["110100"]; 
    $name=["北京市"]; 
    $fcode=$P_fcode; 
  } 
  if($P_fcode=="350000"){ 
    $code=["350100", "350200", "350300", "350400", "350500", "350600", "350700", "350800", "350900"]; 
    $name=["福州市", "厦门市", "莆田市", "三明市", "泉州市", "漳州市", "南平市", "龙岩市", "宁德市"]; 
    $fcode=$P_fcode; 
  } 
  if($P_fcode=="710000"){ 
  } 
  $city=["code"=>$code, "name"=>$name, "fcode"=>$fcode]; 
  return $city; 
} 
function getCounty($P_fcode){ 
  $county=[]; 
  $code=[]; 
  $name=[]; 
  $fcode=[];  
  if($P_fcode=="110100"){ 
    $code=["110101", "110102", "110103", "110104", "110105", "110106", "110107"]; 
    $name=["东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区"]; 
    $fcode=$P_fcode; 
  } 
  if($P_fcode=="350100"){ 
    $code=["350102", "350103", "350104"]; 
    $name=["鼓楼区", "台江区", "苍山区"]; 
    $fcode=$P_fcode; 
  } 
  if($P_fcode=="350200"){ 
    $code=["350203", "350205", "350206"]; 
    $name=["思明区", "海沧区", "湖里区"]; 
    $fcode=$P_fcode; 
  } 
  $county=["code"=>$code, "name"=>$name, "fcode"=>$fcode]; 
  return $county; 
} 
//var_dump($province); 
if($type=="province"){ 
  $province=getProvince(); 
  $retArr["data"]=$province;  
}else if($type=="city"){ 
  $city=getCity($fcode); 
  $retArr["data"]=$city; 
}else if($type="county"){ 
  $county=getCounty($fcode); 
  $retArr["data"]=$county; 
} 
echo json_encode($retArr); 
?> 

Next is cityTemplate.wxml::

<template name="city"> 
<view class="areas"> 
 <view class="province"> 
  <picker bindchange="provincePickerChange" value="{{provinceIndex}}" range="{{province.name}}" data-city-url="{{cityUrl}}"> 
  <text class="select-item">{{province.name[provinceIndex]}}</text> 
  </picker> 
 </view> 
 <view class="city"> 
 <block wx:if="{{!city.name.length}}"> --Second-level city area-- </block> 
 <block wx:if="{{city.name.length>0}}">  
  <picker bindchange="cityPickerChange" value="{{cityIndex}}" range="{{city.name}}" data-county-url="{{countyUrl}}"> 
   <text class="select-item">{{city.name[cityIndex]}}</text> 
  </picker> 
 </block> 
 </view> 
 <view class="county"> 
 <block wx:if="{{!county.name.length}}"> --Three-level area-- </block> 
 <block wx:if="{{county.name.length>0}}"> 
  <picker bindchange="countyPickerChange" value="{{countyIndex}}" range="{{county.name}}"> 
   <text class="select-item">{{county.name[countyIndex]}}</text> 
  </picker> 
 </block> 
 </view> 
</view> 
</template> 

cityTemplate.js::

/** 
 * Obtain three functions for the three-level联动 
 * that:  The instance of the registration page is required 
 * p_url: First-level province URL, required 
 * p_data: First-level province parameters, optional 
 */ 
var net = require( "net" );//Introduce the request method 
var g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method; 
function initCityFun( that, p_url, p_data ) { 
  //Get the first-level province data 
  g_cbSuccess = function( res ) { 
   that.setData({ 
    'city.province': res 
   }); 
  }; 
  net.r( p_url, p_data, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); 
  //Click the first-level picker to trigger the event and get the city and district method 
  var changeProvince = function( e ) { 
    that.setData({ 
      'city.provinceIndex': e.detail.value 
    }); 
    var _fcode = that.data.city.province.code[ e.detail.value ]; 
    if( !_fcode ) { 
      _fcode = 0; 
    } 
    var _cityUrl = e.target.dataset.cityUrl; 
    g_url = _cityUrl + _fcode; 
    g_cbSuccess = function( res ) { 
      that.setData({ 
        'city.city': res 
      }); 
    } 
    net.r( g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); 
  }; 
  that[ "provincePickerChange" ] = changeProvince; 
  //Click the second-level picker to trigger the event and get the region method 
  var changeCity = function( e ) { 
    that.setData({ 
      'city.cityIndex': e.detail.value 
    }); 
    var _fcode = that.data.city.city.code[ e.detail.value ]; 
    if( !_fcode ) { 
      _fcode = 0; 
    } 
    var _countyUrl = e.target.dataset.countyUrl; 
    g_url = _countyUrl + _fcode; 
    g_cbSuccess = function( res ) { 
      that.setData({ 
        'city.county': res 
      }); 
    }; 
    net.r( g_url, g_datd, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); 
  }; 
  that[ "cityPickerChange" ] = changeCity; 
  //Click the third-level picker to trigger the event 
  var changeCounty = function( e ) { 
    that.setData({ 
      'city.countyIndex': e.detail.value 
    }); 
  }; 
  that["countyPickerChange"] = changeCounty; 
} 
function getProvinceFun(that, p_url, p_data){ 
  g_cbSuccess = function( res ) { 
   that.setData({ 
    'city.province': res 
   }); 
  }; 
  net.r( p_url, p_data, g_cbSuccess, g_cbSuccessErr, g_cbFail, g_cbComplete, g_header, g_method ); 
} 
module.exports={ 
  initCityFun: initCityFun, 
  getProvinceFun: getProvinceFun 
} 

By the way, net.js method: :

/** 
 * send http request through the network, default return type is json 
 *  
 * url: must, other parameters are not required, interface address 
 * data: parameters for the request Object or String 
 * successFun(dts): callback function for successful return, data added by WeChat is automatically filtered, according to the interface agreement, return the data after success, filter out msg and status 
 * successErrorFun(msg): the request is executed successfully, but the server considers it a business error, execute other actions, default pop system prompt information. 
 * failFun: callback function when the interface call fails 
 * completeFun: callback function when the interface call ends (executed for both success and failure) 
 * header: object, sets the request header, Referer cannot be set in header 
 * method: default is GET, valid values: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT 
 *  
 */ 
function r( url, data, successFun, successErrorFun, failFun, completeFun, header, method ) { 
  var reqObj = {}; 
  reqObj.url = url; 
  reqObj.data = data; 
  //default header is json 
  reqObj.header = { 'Content'-Type': 'application'/json' }; 
  if( header ) { 
    //Override header 
    reqObj.header = header; 
  } 
  if( method ) { 
    reqObj.method = method; 
  } 
  reqObj.success = function( res ) { 
    var returnData = res.data; //Filter the result on the WeChat side to get the original data returned by the server 
    var status = returnData.status; //Only call the success function when returning status as agreed by the interface 
    //console.log(res); 
    //Normal business function execution 
    if( status == true ) { 
      if( successFun ) { 
        var dts = returnData.data; 
        successFun( dts );//Callback, equivalent to processing and assigning data directly in the callback after obtaining the data 
      } 
    } else if( status == false ) { 
      var msg = returnData.msg; 
      if( !successErrorFun ) { 
        console.log( msg ); 
      } else { 
        successErrorFun( msg ); 
      } 
    } else { 
      console.log( "The server did not return data in the agreed format of the interface" ); 
    } 
  } 
  reqObj.fail = function( res ) { 
    if( failFun ) { 
      failFun( res ); 
    } 
  } 
  reqObj.complete = function( res ) { 
    if( completeFun ) { 
      completeFun( res ); 
    } 
  } 
  wx.request( reqObj ); 
} 
module.exports = { 
  r: r 
} 

The core code is the three files above, and the next is the demo file for testing::

demo.wxml::

<import src="../../template/cityTemplate.wxml"/> 
<template is="city" data="{{...city}}" /> 

demo.js::

var city = require( '../../common/cityTemplate' ); 
Page( { 
 data: {}} 
 }, 
 onLoad: function(options) { 
  var _that = this; 
  //Create a three-level联动 data object ---- This city object is fixed, only the request URL is changed according to the server address of each service end 
  _that.setData({ 
   city: { 
    province: {},//Format: province:{code: ["11000", "12000"], name: ["Beijing City", "Shanghai City"]}, only name and code can be fixed because the template needs to display according to these two parameters 
    city: {}, 
    county: {}, 
    provinceIndex: 0, 
    cityIndex: 0, 
    countyIndex: 0, 
    cityUrl: "http://localhost:8282/phpserver/areas.php#63;type=city&fcode="//;type indicates the region to be obtained, fcode is the first-level code, it will be modified according to the backend request parameters at that time 
    countyUrl: "http://localhost:8282/phpserver/areas.php#63;type=county&fcode=" 
   } 
  ) 
  var _url = "http://localhost:8282/phpserver/areas.php"; 
  var _data = {'type': 'province', 'fcode': '0'}; 
  city.initCityFun(_that, _url, _data); 
 } 
) 

The complete code file tested above is as follows:

There is a bug here, when the pull-down refresh and picker component are opened, the pull-downs overlap. I don't know if it is due to the development tool or if it is still a bug that has not been fixed... I can only wait for the update of the message from WeChat to give feedback.

Thank you for reading, I hope it can help everyone, thank you everyone for your support to our website!

You May Also Like