小程序循环列表点击展开收缩

之前在网上找了很多文章,要么没有循环,要么格式不是我想要的。最后看到了一篇大佬的文章https://blog.csdn.net/haishangfeie/article/details/81040211。大佬的是树结构,和循环列表很相似,只不过查看二级数据的时候会覆盖首级数据,对于想要直观的查看每一级的数据可能不太方便,所以动手吧,就有了下面这种可以无限循环的列表。 

直接放代码吧,代码记得放在components里面

wxml

<view>
  <scroll-view style="background:white" class="con">
    <view bindtap='tapItem' data-id='{{ model.id }}' data-text='{{ model.name }}' data-nodes="{{model.nodes}}" class="text">{{ model.name }}</view>
    <view wx:if='{{ isBranch }}' bindtap='toggle' class="img">
      <image src=" {{ open ? '../../images/down.png' : '../../images/right1.png' }}"></image>
    </view>
    <view wx:else class="imgnone"> </view>
  </scroll-view>
    <view wx:if='{{ isBranch }}' hidden='{{ !open }}'>
    <mytree wx:for='{{ model.nodes }}' wx:key='id' model='{{ item }}'></mytree>
  </view>
 </view>

js

Component({
  properties: {
    model: Object,
  },

  data: {
    open: false,
    isBranch: false,
  },

  methods: {
    toggle: function (e) {
      if (this.data.isBranch) {
        this.setData({
          open: !this.data.open,
        })
      }
    },

    tapItem: function (e) {
      var itemid = e.currentTarget.dataset.id;
      var text = e.currentTarget.dataset.text;
      var nodes = e.currentTarget.dataset.nodes
      this.triggerEvent('tapitem', { id: itemid, text: text,nodes:nodes},{ bubbles: true, composed: true }); 
      //console.log('arr', this.properties.model)
    },
    
  },

  ready: function (e) {
    //console.log(this.data);
    this.setData({
      isBranch: Boolean(this.data.model.nodes && this.data.model.nodes.length),
    });
   
  },
})

wxss

/* pages/tree/tree.wxss */
.con image{
  width: 25px;
  height: 25px;
  margin-top: 12px;
}
.con{
  width: 100%;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid rgb(228, 227, 227);
}
.text{
  float: left;
  margin-left: 3%;
  width: 60%;
}
.img{
  text-align: right;
}
.imgnone{
  width: 100%;
  height: 100%;
  background-color: rgb(241, 246, 247);
}

json

{
  "component": true,
  "usingComponents": {
    "mytree": "../tree/tree"
  }
}

 用的时候,treeData就是你要放进去的数据。点击文字的时候调用tapItem方法,可以查看点击的数据内容,可以用来赋值或者查询数据。点击向右的图标,展开当前层级下面的子级。当前层级无子级时,向右图标隐藏。

<view wx:for="{{treeData}}" wx:key="index" class="model">
  <mytree model='{{item}}' bind:tapitem='tapItem' style="display:{{hid}}">
  </mytree>
</view>
tapItem: function (e) {
    var str = e.detail
    console.log(e)
  },

treeData的数据结构是这样的。到此为止,你就可以无限的循环展开列表啦。如果你的数据结构和我的不太一样,记得去wxml和js里面更改一下属性名称。

 

 

 

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值