之前在网上找了很多文章,要么没有循环,要么格式不是我想要的。最后看到了一篇大佬的文章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里面更改一下属性名称。