小程序自定义组件嵌套-小程序自定义组件意义-微信小程序组件开发
1.
小程序有一个需求:实现树形菜单,因为数据是动态的,所以页面没办法写死,想到了无限嵌套
2.组件的嵌套其实就是让自定义组件引用自身,然后页面直接使用该组件就可以
3.自定义组件的使用:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/
4.1.自定义组件(树形菜单)
viewstyle'margin-left:{{depth*20}}px'wx:if"{{treedata.length0}}"wx:for"{{treedata}}"viewdata-id"{{item.id}}"{{item.name}}/viewviewwx:if"{{item.childs!undefineditem.childs!nullitem.childs.length0}}"servanttreedata"{{item.childs}}"depth"{{depth+1}}"/servant/view/view5.组件实现自引用必须在自定义组件的json文件中添加usingComponents
{"component":true,//声明组件"usingComponents":{//可以使用的组件"servant":"/components/master/master"}}6.同时组件的js文件中需要定义属性,其他页面使用该组件时数据通过这个属性传递
Component({/***组件的属性列表*/properties:{treedata:{type:Array,value:[]},depth:{type:Number,value:0}},/***组件的初始数据*/data:{},/***组件的方法列表*/methods:{}})7.2.组件定义完成后,页面使用
8.页面json文件需要声明
{"usingComponents":{"servant":"/components/master/master"//组件路径}}!--数据是在页面的js中定义的,通过组件的属性treedata来传递--servanttreedata"{{treedata}}"depth"0"/servant9.示例数据,数据在使用组件的js中
Page({data:{treedata:[{id:1,name:"第一层1",childs:[{id:2,name:"第二层11",childs:[{id:4,name:"第三层11",childs:[{id:5,name:"第四层11",childs:[]},{id:6,name:"第四层12"}]},{id:7,name:"第三层12"}]},{id:3,name:"第二层12"}]},{id:2,name:"第一层2",childs:[{id:8,name:"第二层21",childs:[{id:9,name:"第三层21",childs:[{id:10,name:"第四层21",childs:[{id:14,name:"第五层"}]}]},{id:12,name:"第三层22"}]},{id:13,name:"第二层22"}]}]}})10.效果图(有点丑,哈哈哈)
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

