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

WeChat development: using picker to encapsulate the template of province, city, and district linkage

Currently, learning WeChat Mini Programs is more about whether it can encapsulate other components twice, which is conducive to quickly developing various WeChat Mini Programs in the future. Currently, it has been found that the selector mode of picker only has one level of dropdown. Then, can we use3How can we use a picker to implement a three-level联动 template form to introduce other pages? The answer is definitely yes. So my idea is like this:

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

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

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

Then, let's talk about the directory structure of my demo:

common

    -net.js//wx.request 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 with phpstudy for testing. Don't ask me why the server is like this, I don't understand 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 mark 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=["Beijing City"]; 
  $fcode=$P_fcode; 
 } 
 if($P_fcode=="350000"){ 
  $code=["350100", "350200", "350300", "350400", "350500", "350600", "350700", "350800", "350900"]; 
  $name=["Fuzhou City", "Xiamen City", "Putian City", "Sanming City", "Quanzhou City", "Zhangzhou City", "Nanping City", "Longyan City", "Ningde City"]; 
  $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=["Dongcheng District", "Xicheng District", "Chongwen District", "Xuanwu District", "Chaoyang District", "Fengtai District", "Shijingshan District"]; 
  $fcode=$P_fcode; 
 } 
 if($P_fcode=="350100"){ 
  $code=["350102", "350103", "350104"]; 
  $name=["Gulou District", "Taijiang District", "Cangshan District"]; 
  $fcode=$P_fcode; 
 } 
 if($P_fcode=="350200"){ 
  $code=["350203", "350205", "350206"]; 
  $name=["Siming District", "Haicang District", "Huli District"]; 
  $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); 
?> 

The following 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 and district-- </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::

/** 
 * Get three functions for three-level联动 
 * that: The this instance of the registration page, required 
 * p_url: URL for first-level province, required 
 * p_data: Optional parameter for first-level province 
 */ 
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-county 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: :

/** 
 * Network sends http request, default return type is json 
 * 
 * url: Must be provided, other parameters are not required, interface address 
 * data: Parameters for request, Object or String 
 * successFun(dts): Callback function for successful return, data added by WeChat end is automatically filtered out, 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 and performs other actions, the default system prompt information is popped up. 
 * failFun: Callback function for interface call failure 
 * completeFun: Callback function after interface call ends (both success and failure will execute) 
 * 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 of the WeChat end, and obtain the original data returned by the server 
  var status = returnData.status; //Only call the success function when returning status as agreed in 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 
   } 
  } 
   var msg = returnData.msg; 
   if(!successErrorFun) { 
    console.log(msg); 
   } 
    successErrorFun(msg); 
   } 
  } 
   console.log('The server did not return data in the agreed interface format'); 
  } 
 } 
 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 above three files, 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, and only the requested URL changes according to the service endpoint address. 
 _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 area to be obtained, fcode is the first-level code, and it will be modified according to the backend request parameters later 
  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 is tested as follows:

There is a bug here, the pull-down refresh and the picker component overlap when they are opened. I don't know if it's due to the development tool or if it's still a bug that needs to be fixed. I can only wait for updates from WeChat to give feedback.

That's all for this article, I hope it will be helpful to everyone's study, and I also hope that everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When sending an email, please replace # with @ to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like