小程序中的樹形控件

參考:https://segmentfault.com/a/1190000021286232
工作了一段時(shí)間,很久沒寫關(guān)于代碼上的學(xué)習(xí)記錄,這是在公司處理一個(gè)樹形控件時(shí)尋找解決方法時(shí)看到的一篇文章,很有效地幫助到我掉瞳,非常感謝O帧癞揉!

因?yàn)楣镜脑?對代碼進(jìn)行了一些修改,但總體的操作理念比較符合我的需求。

以下的代碼都是關(guān)于微信小程序作為開發(fā)

首先先新建一個(gè)放自定義組件的文件夾(components),組件的名稱根據(jù)自己的開發(fā)來定義,我這邊就稱它為(tree)組件,下面為tree組件的全部代碼
(技巧:新建組件文件一般都是右鍵點(diǎn)擊文件夾-然后選擇 '新建Component'-這樣就能快速新建一個(gè)組件文件)也不算啥技巧精盅,估計(jì)大家都知道#125

tree.wxml

\triangleright 有些wx:if的判斷可以暫時(shí)沒用,因?yàn)楣敬a用到,所以我就直接復(fù)制上去了(我比較懶)渔嚷,還有里面用到的圖片(tick.png),只是一張打勾的圖片稠曼,隨便上網(wǎng)找下就是了

<view>
    <block wx:for="{{tree}}" wx:key="index">
        <view style="display:flex;align-items:center;margin-left:{{item.nodes.length !== 0 ? depth*20 : depth*30}}px;font-size:36rpx;margin-top: 5px;"
            wx:if="{{item.category !== 'index'}}">
            <view class="tree_left" wx:if="{{item.nodes.length !== 0}}" data-id="{{item.id}}" data-open="{{item.open}}"
                bindtap="onchange">
                <view class="{{!item.open ? 'icon-right' : 'icon-down'}}"></view>
            </view>

            <view class="{{item.nodes.length !== 0 ?'parent':'node'}} " data-id="{{item.id}}" data-open="{{item.open}}"
                bindtap="onchange">
                {{item.name}}
                <view class="selected" wx:if="{{item.category !== 'index'}}" catchtap="handleClick"
                    data-id="{{item.id}}" data-value="{{item.name}}">
                    <image hidden="{{item.selected === false}}" src="../../pages/image/tick.png"
                        style="width:20px;height:20px;"></image>
                </view>
            </view>
        </view>
        <block wx:if="{{item.nodes}}">
            <view hidden="{{!item.open}}">
                <tree treeList="{{item.nodes}}" id="treeSelect" bind:onclick="click" bind:change="change"
                    depth="{{depth+1}}"></tree>
            </view>
        </block>
    </block>
</view>

tree.wxss

.tree_left{
    position: relative;
    float: left;
}

.icon-down{
    border: 8px solid;
    border-color: transparent transparent #B8B8B8;
    transform: rotate(180deg);
    margin-top: 7px;
    margin-left: 5px;
    margin-right: 10px;
}

.icon-right{
    border: 8px solid;
    border-color: transparent transparent #B8B8B8;
    transform: rotate(90deg);
    margin-left: 5px;
}

.selected{
    height: 20px;
    width: 20px;
    border-radius: 50%;
    border: 1px solid #D6D6D6;
    float: right;
    margin-left: 5px;
    margin-top: 2px;
}

tree.js

const tranverse = (e) => {
    for (let i in e) {
        if (e[i].nodes) {
            e[i].open = false;
            tranverse(e[i].nodes)
        }
        e[i].selected = false;
    }
}
Component({
    properties: {
        treeList: Object,
        depth: {
            type: Number,
            value: 0
        }
    },
    data: {},
    ready() {
        // const {treeList}=this.properties; 
        const { treeList } = this.data;
        for (let i in treeList) {
            if (treeList[i].nodes) {
                treeList[i].open = false;
                tranverse(treeList[i].nodes);
            }
            treeList[i].selected = false;
        }
        this.setData({
            tree: treeList
        })
    },
    methods: {
        //修改折疊狀態(tài)
        changeOpen(tree, id) {
            for (let i = 0; i < tree.length; i += 1) {
                if (tree[i].id === id) {
                    tree[i].open = !tree[i].open;
                }
                if (tree[i].nodes.length !== 0) {
                    this.changeOpen(tree[i].nodes, id);
                }
            }
            return;
        },
        onchange(e) {
            const { treeList } = this.data;
            const { id } = e.currentTarget.dataset;
            this.changeOpen(treeList, id);
            this.triggerEvent('change', id, { bubbles: true, composed: true });
            this.setData({
                tree: treeList
            })
        },
        change(e) {
            const id = e.detail;
            const { treeList } = this.data;
            this.changeOpen(treeList, id);
            this.setData({
                tree: treeList
            })
        },
        click(e) {
            const t = this.selectAllComponents('#treeSelect');
            t.forEach(item => {
                item.click(e);
            })
            let id = '';
            if (e.detail) {
                id = e.detail.id;
            }
            const { treeList } = this.data;
            this.setStatus(treeList, id);
            this.setData({
                tree: treeList
            })
        },
        handleClick(e) {
            const t = this.selectAllComponents('#treeSelect');
            t.forEach(item => {
                item.click(e);
            })
            //   const {id}=e.currentTarget.dataset;
            const { id, value } = e.currentTarget.dataset;
            const { treeList } = this.data;
            // const value = this.getData(treeList, id)
            this.setStatus(treeList, id);
            this.triggerEvent('onclick', { id, value, treeList }, { composed: true, bubbles: true });
            this.setData({
                tree: treeList
            })
        },
        //切換選中狀態(tài)
        setStatus(tree, id) {
            for (let i = 0; i < tree.length; i += 1) {
                if (tree[i].id == id) {
                    tree[i].selected = true;
                } else {
                    tree[i].selected = false;
                }
                if (tree[i].nodes) {
                    this.setStatus(tree[i].nodes, id);
                }
            }
            return;
        },
        //獲取選中項(xiàng)信息
        getData(tree, id) {
            for (let i = 0; i < tree.length; i += 1) {
                if (tree[i].id === id) {
                    return tree[i].name;
                }
                if (tree[i].nodes) {
                    this.getData(tree[i].nodes, id);
                }
            }
            return '';
        },
    }
})

tree.json

{
    "component": true,
    "usingComponents": {
        "tree": "/components/tree/tree"
    }
}

當(dāng)你寫完這個(gè)tree組件的時(shí)候形病,是時(shí)候驗(yàn)證它的展示效果,
注意:這里的數(shù)據(jù)是寫死的,請根據(jù)自己開發(fā)需求進(jìn)行代碼上的修改

隨便新建一個(gè)Page頁面,為demo頁面

demo.wxml

\triangleright 這個(gè)treeList傳的內(nèi)容為一個(gè)數(shù)組對象霞幅,如:[{..},{...}]漠吻,這樣子的數(shù)據(jù)

<tree treeList="{{treeList}}" id="treeSelect" bind:onclick="treeClick"></tree>

demo.wxss

/* 這里沒寫樣式,可以自己設(shè)計(jì) */

demo.json

\triangleright 這里路徑一般根據(jù)自己的項(xiàng)目文件來引用,并不一定要按我的寫法

{
   "usingComponents": {
    "tree": "../../components/tree/tree"
  }
}

demo.js

Page({
     data: {
        treeList: [
            {
                id: '1',
                pid: '0',
                name: '祖先節(jié)點(diǎn)',
                nodes:[
                    {
                        id: '1-1',
                        pid: '1',
                        name: '父節(jié)點(diǎn)1',
                        nodes:[
                            {
                                id: '1-1-1',
                                pid: '1-1',
                                name: '子節(jié)點(diǎn)1',
                                nodes: []
                            }
                        ]
                    },
                    {
                        id: '1-2',
                        pid: '1',
                        name: '父節(jié)點(diǎn)2',
                        nodes:[
                            {
                                id: '1-1-2',
                                pid: '1-1',
                                name: '子節(jié)點(diǎn)2',
                                nodes: []
                            }
                        ]
                    }
                ]
            }
        ]
    },

    treeClick(e) {
        console.log(e)
        const t = this.selectAllComponents('#treeSelect');
        t.forEach(item => {
            item.click(e);
        })
        const { id, value } = e.detail;
        console.log(e.detail)
    }
})

展示效果如下:


樹形控件.gif

總結(jié):剛開始做公司的這個(gè)需求的時(shí)候,感覺難度應(yīng)該不大,可惜我是程序員中的菜雞,需要找資料才能解決掉,不懂就百度司恳,這是個(gè)日常的操作途乃。不說那么多廢話,這個(gè)樹形控件的使用請留意原文章作者的描述(描述的非常詳細(xì)),因?yàn)橹坝玫臉湫慰丶际遣荒軌蜻M(jìn)行單選的操作,所以尋找了很多處理方法都搞不掂扔傅,最后找到了這邊文章耍共,并在原代碼進(jìn)行一定的修改,發(fā)現(xiàn)可以滿足我的需求猎塞,這是非常不錯(cuò)的J远痢!這里再次感謝寫這篇文章的作者荠耽,因?yàn)檎娴膸偷轿伊?哈哈哈钩骇,請?jiān)徫沂遣穗u。

當(dāng)然這個(gè)樹型控件還是存在一些缺陷,假如節(jié)點(diǎn)越來越多又或者節(jié)點(diǎn)上的文字寬度占的比例較大的話,會(huì)顯得比較丑陋,還是需要多加改進(jìn)铝量。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末倘屹,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子款违,更是在濱河造成了極大的恐慌唐瀑,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件插爹,死亡現(xiàn)場離奇詭異哄辣,居然都是意外死亡请梢,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門力穗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來毅弧,“玉大人,你說我怎么就攤上這事当窗」蛔” “怎么了?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵崖面,是天一觀的道長元咙。 經(jīng)常有香客問我,道長巫员,這世上最難降的妖魔是什么庶香? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮简识,結(jié)果婚禮上赶掖,老公的妹妹穿的比我還像新娘。我一直安慰自己七扰,他們只是感情好奢赂,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著颈走,像睡著了一般膳灶。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上疫鹊,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天袖瞻,我揣著相機(jī)與錄音,去河邊找鬼拆吆。 笑死聋迎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的枣耀。 我是一名探鬼主播霉晕,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼捞奕!你這毒婦竟也來了牺堰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤颅围,失蹤者是張志新(化名)和其女友劉穎伟葫,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體院促,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡筏养,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年斧抱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渐溶。...
    茶點(diǎn)故事閱讀 40,146評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡辉浦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出茎辐,到底是詐尸還是另有隱情宪郊,我是刑警寧澤,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布拖陆,位于F島的核電站弛槐,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏慕蔚。R本人自食惡果不足惜丐黄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望孔飒。 院中可真熱鬧,春花似錦艰争、人聲如沸坏瞄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鸠匀。三九已至,卻和暖如春逾柿,著一層夾襖步出監(jiān)牢的瞬間缀棍,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工机错, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留爬范,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓弱匪,卻偏偏與公主長得像青瀑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子萧诫,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評論 2 356

推薦閱讀更多精彩內(nèi)容