文章目錄
- 一、為什么要用樹結(jié)構(gòu)?
-
二、使用步驟
- 1.引入相關(guān)json
- 2.樹結(jié)構(gòu)的轉(zhuǎn)換
- 總結(jié)
一、為什么要用樹結(jié)構(gòu)?
本文將講述一個實(shí)例,構(gòu)造一棵樹來實(shí)現(xiàn)數(shù)組和tree的轉(zhuǎn)換,這在前端樹結(jié)構(gòu)中是經(jīng)常遇到的
后端返回樹結(jié)構(gòu)方便管理,前端也只需要請求一次接口拿到所有數(shù)據(jù)
前端樹轉(zhuǎn)成數(shù)組后的效果圖:
二、使用步驟
1.引入相關(guān)json
代碼如下(示例):請下載資源
2.讀入數(shù)據(jù)
代碼如下(示例):文章來源:http://www.zghlxwxcb.cn/news/detail-664808.html
<!--
* @author:yxm
* @description復(fù)用教材
-->
<template>
<div class="whole-title-bj">
<ul class="whole-title" v-for="(item,index) in Object.keys(dataForm)" :key="index">
<li class="title-left">{{item}}</li>
<li class="title-right">
<div
v-for="(item2, index2) in dataForm[item]"
:key="index2"
class="title-right-name common-cursor"
:class="{ 'activate-index': selectForm[item] == item2.tag_id }"
@click="selectClick(item, item2)"
>
{{ item2.tag_name }}
</div>
</li>
</ul>
</div>
</template>
<script>
import nationalJson from "./national_lesson_tag.json" //測試
export default {
name: '',
data () {
return {
dataForm:{},//源數(shù)據(jù)
selectForm:{},//選中當(dāng)前
selectMap:{},
}
},
mounted(){
this.initData(nationalJson.hierarchies[0])//測試
},
methods: {
// 初始化數(shù)據(jù)遞歸
initData(data) {測試
let children = data.children;
let hierarchy_name = data.hierarchy_name;
let item = children[0];
let tag_name = item.tag_name;
this.$set(this.dataForm, hierarchy_name, children);
this.$set(this.selectForm, hierarchy_name, item.tag_id);
this.$set(this.selectMap, tag_name, item.tag_name);
if(item.hierarchies) {
this.initData(item.hierarchies[0]);
}
},
// 點(diǎn)擊選擇教材
selectClick(item, tag) {
this.selectForm[item] = tag.tag_id;
if(tag.children) {
this.initData(tag.children[0]);
}
console.log(this.selectForm);
},
},
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css類 */
.whole-title-bj {
width: 90%;
.whole-title {
display: flex;
flex-wrap: wrap;
align-items: baseline;
.title-left {
margin-right: 25px;
color: #999999;
}
.title-right {
width: 90%;
display: flex;
flex-wrap: wrap;
line-height: 30px;
&-name {
padding: 0 20px;
margin-bottom: 16px;
margin-right: 20px;
color: #000000;
}
}
}
.activate-index {
color: #1e62ec !important;
background: rgba(30, 98, 236, 0.1);
border-radius: 17px;
font-size: 14px;
}
}
</style>
總結(jié)
使用遞歸把樹轉(zhuǎn)成列表數(shù)組,使得接口請求一次,前端自己組裝結(jié)構(gòu)文章來源地址http://www.zghlxwxcb.cn/news/detail-664808.html
到了這里,關(guān)于樹結(jié)構(gòu)使用實(shí)例---實(shí)現(xiàn)數(shù)組和樹結(jié)構(gòu)的轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!