微信小程序 頁面遞歸生成


最近寫小程序,有一個選擇行業的需求,准備實現以下效果:

                                    

 

使用van-collapse和單選按鈕實現。

遇到一個問題,不知道需要遞歸幾層,寫死10個,8個應該也是可以的,估計會繞暈,哈哈~

網上查了一下,可以使用組件(Component)的方式實現。

具體實現如下:

1、創建component的文件夾,再創建collapse-radio文件夾,右鍵 點擊 “新建Component”,取名index,生成組件。結構如下:

2、index.wxml文件的代碼如下:

<!--component/collapse-radio/index.wxml-->
<van-collapse value="{{ activeName[item.id] }}" data-id="{{item.id}}" bind:change="onChange" accordion>
  <view wx:for="{{item.children}}" wx:key="id">
    <van-collapse-item wx:if="{{!item.is_leaf}}" title="{{item.name}}" name="{{item.id}}" data-index="{{index}}" data-id="{{item.id}}">
      <collapse-radio item="{{item}}"></collapse-radio>
    </van-collapse-item>
    <view wx:else> 
      <van-cell title="{{item.name}}" value-class="value-class">
        <van-radio name="{{item.id}}" />
      </van-cell>
    </view>
  </view>
</van-collapse>

3、index.js代碼如下:

// component/collapse-radio/index.js
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    item: Object
  },

  /**
   * 組件的初始數據
   */
  data: {
    activeName: {}
  },

  /**
   * 組件的方法列表
   */
  methods: {
    // 展開面板
    onChange(event) {
      console.log(event);
      const id = event.target.dataset.id;
      const activeName = this.data.activeName;
      activeName[id] = event.detail;
      console.log(activeName);
      this.setData({
        activeName: activeName
      });
    }
    
  }
})

4、在app.json中配置組件:

5、在頁面中使用

<van-radio-group>
  <collapse-radio item="{{item}}"></collapse-radio>
</van-radio-group>

6、js代碼

const list = [{
  id: '1',
  name: '金融業',
  is_leaf: 0,
  children: [{
    id: '11',
    name: '銀行業',
    is_leaf: 0,
    children: [{
      id: '111',
      name: '中央銀行',
      is_leaf: 1
    }, {
      id: '112',
      name: '商業銀行',
      is_leaf: 1
    }, {
      id: '113',
      name: '其他銀行',
      is_leaf: 1
    }]
  }, {
    id: '12',
    name: '證券業',
    is_leaf: 1
  }, {
    id: '13',
    name: '保險業',
    is_leaf: 0
  }]
},{
  id: '2',
  name: '教育業',
  is_leaf: 1
}, {
  id: '3',
  name: '房地產業',
  is_leaf: 0
}];
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    item:{
      id: '0',
      name: '',
      is_leaf: 0,
      children:list
    }
  },
  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函數--監聽頁面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函數--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命周期函數--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函數--監聽頁面卸載
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函數--監聽用戶下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函數
   */
  onReachBottom: function () {

  },

  /**
   * 用戶點擊右上角分享
   */
  onShareAppMessage: function () {

  }
})

就可實現遞歸效果。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM