一、預覽
微信小程序在自帶的表單組件中加入了選擇器picker,并給出了常用的時間和省市區(qū)三級聯(lián)動選擇器,但日常開發(fā)中不可能僅僅使用這些選擇器,所以我們在學習時先寫一個常見的自定義選擇器,用于滿足項目中的日常需要。
先給出效果圖:(先聲明選擇器中數(shù)據(jù)為測試使用,與真實情況無關)

二、picker屬性
一個簡單地多列選擇器只要給picker組件加屬性mode="multiSelector"即可,綁定數(shù)據(jù)時使用range來綁定一個數(shù)組作為顯示內容,下面是官方給出的屬性解釋。

三、創(chuàng)建組件
我們可以先在.wxml建一個自定義picker組件:
<picker mode="multiSelector" bindchange="bindCustomPickerChange" bindcolumnchange="bindCustomPickerColumnChange" value="{{customIndex}}" range="{{onlyArray}}" > <view> 多列自創(chuàng)選擇器:{{onlyArray[0][customIndex[0]]}},{{onlyArray[1][customIndex[1]]}},{{onlyArray[2][customIndex[2]]}} </view></picker>要注意的是,此處的onlyArray數(shù)組只是當前顯示內容的數(shù)組,并不是我們全部數(shù)據(jù)的數(shù)組。
四、自定義函數(shù)
寫好組件,我們就來寫js文件,思路如下:
1.先創(chuàng)建頁面所需數(shù)據(jù)
Page({ /** * 頁面的初始數(shù)據(jù) */ data: { //當前選中數(shù)組的下標值 customIndex: [0, 0, 0], //當前選中數(shù)組 onlyArray: [ [], [], [] ], //customArray假設為我們從后臺獲取到的json數(shù)據(jù) customArray: [{ name: '百度', dept: [{ name: '搜索', product: [{ name: '百度搜索' }, { name: '百度一下' }, ] }, { name: '團購', product: [{ name: '百度糯米' }, { name: '餓了么' }] }, { name: '音樂', product: [{ name: '百度音樂' }] }, { name: '問答社區(qū)', product: [{ name: '百度貼吧' }] } ] }, { name: '騰訊', dept: [{ name: '社交', product: [{ name: 'QQ' }, { name: '微信' }, ] }, { name: '視頻', product: [{ name: '騰訊視頻' }, { name: '搜狐視頻' }, ] }, { name: '短視頻', product: [{ name: '微視' }] } ] }, ], },2.加載頁面時給出賦值函數(shù)。
可以看到,當前選中數(shù)組onlyArray是空的,在小程序顯示時會直接顯示成空,所以需要在頁面創(chuàng)建時給一個初始值,這個初始值使用customIndex數(shù)組來給出,也可以用于頁面數(shù)據(jù)回填。代碼如下:
/** * 生命周期函數(shù)--監(jiān)聽頁面加載 */ onLoad: function(options) { var data = { customArray: this.data.customArray, customIndex: this.data.customIndex, onlyArray: this.data.onlyArray, }; for (var i = 0; i < data.customArray.length; i++) { data.onlyArray[0].push(data.customArray[i].name); } for (var j = 0; j < data.customArray[data.customIndex[0]].dept.length; j++) { data.onlyArray[1].push(data.customArray[data.customIndex[0]].dept[j].name); } for (var k = 0; k < data.customArray[data.customIndex[0]].dept[data.customIndex[1]].product.length; k++) { data.onlyArray[2].push(data.customArray[data.customIndex[0]].dept[data.customIndex[1]].product[k].name); } this.setData(data); },
新聞熱點
疑難解答