微信小程序 页面递归生成

最近写小程序,有一个选择行业的需求,准备实现以下效果:

                                    

使用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 () {

  }
})

就可实现递归效果。

猜你喜欢

转载自www.cnblogs.com/zhaidq/p/11227532.html