效果展示:點擊按鈕--->出現樹-->選中數據-->展示在頁面
邏輯:樹組件,獲取選中數據,找到父節點,傳給父組件
遇到的問題:節點有key和jiancheng兩個數據,要寫上parent記錄父節點,在獲取選中節點的父節點數據時好獲取
效果:
代碼:
子組件(樹結構):
html
<el-tree
class="org-tree"
ref="orgTree"
:data="data"
:props="defaultProps"
node-key="zhujian"
show-checkbox
:default-expanded-keys="['1']"
:render-after-expand="true"
:expand-on-click-node="false"
:highlight-current="true"
@check="nodeClick"
@check-change="handleCheck"
>
<span slot-scope="{ node }" class="custom-tree-node">
<span v-if="node.label" class="el-icon"><i class="el-icon-office-building"></i></span>
<span>{{ node.label }}</span>
</span>
</el-tree>
ts
$refs!: {
orgTree: any
}
datas: any[]=[]
data: any[] = [
{
zhujian: '0',
jiancheng: '中國鐵道建築總公司',
children: [
{
zhujian: '1',
jiancheng: '中國鐵建股份有限公司',
children: [
{
parent: '1',
zhujian: '101',
jiancheng: '信息化管理部'
},
{
parent: '1',
zhujian: '102',
jiancheng: '經濟管理部'
},
{
parent: '1',
zhujian: '103',
jiancheng: '國際部'
},
]
},
{
parent: '0',
zhujian: '10',
jiancheng: '中土集團',
children: [
{
parent: '10',
zhujian: '1001',
jiancheng: '尼日利亞國別公司'
},
{
parent: '10',
zhujian: '1002',
jiancheng: '埃塞俄比亞國別公司'
},
{
parent: '10',
zhujian: '1003',
jiancheng: '東南非區域市場'
},
{
parent: '10',
zhujian: '1004',
jiancheng: '中東北非區域市場'
}
]
},
{
zhujian: '11',
jiancheng: '中鐵十一局',
}
]
//獲取數據方法
handleCheck(data,checked,indeterminate){
let nodes = this.$refs.orgTree.getCheckedNodes().concat(this.$refs.orgTree.getHalfCheckedNodes())
let filterNodes = nodes.filter(node=>{ // 過濾出子節點,也就是不含childred字段的節點數據
return node.children === undefined
})
let node: any[]=[]
for(var i=0 ;i<filterNodes.length;i++){
if(filterNodes[i].parent){
let pnode= this.$refs.orgTree.getNode(filterNodes[i].parent) //獲取父節點
let parent=pnode.data.jiancheng
node[i]=parent+"/"+filterNodes[i].jiancheng
}
else{
node[i]=filterNodes[i].jiancheng
}
}
this.datas=node
this.$emit('getdata',this.datas) //傳數據給父節點
}
父組件
html
<el-form-item prop="apply" label="適用範圍 :">
<el-button style="width:100%" @click="showOrgTree">選擇單位/組織</el-button>
<dialog-org-tree ref="dialogOrgTree" @getDatas="getDatas"></dialog-org-tree>
</el-form-item>
<el-table :data="datas" border stripe height="200px">
<el-table-column type="index" label="序號" width="50px" ></el-table-column>
<el-table-column prop="datas" label="適用範圍">
<template slot-scope="scope" prop="datas">{{ scope.row}}</template>
</el-table-column>
</el-table>
ts
getDatas(data) {
this.datas = data
}
知識點:
1.handleCheck(data,checked,indeterminate)方法獲取數據
2.this.$emit("父組件方法名",data) //data是要傳遞的數據
2. 數據展示:
<template slot-scope="scope" prop="datas">{{ scope.row}}</template>