以下需要用到的api :
check-strictly : 在顯示復選框的情況下,是否嚴格的遵循父子不互相關聯的做法,默認為 false
node-key :每個樹節點用來作為唯一標識的屬性,整棵樹應該是唯一的
setChecked : 通過 key / data 設置某個節點的勾選狀態,使用此方法必須設置 node-key 屬性
check-on-click-node : 是否在點擊節點的時候選中節點,默認值為 false,即只有在點擊復選框時才會選中節點。 ( 如果需要隱藏父節點的勾選按鈕,則這個不能設置為 true)
補充:
修改 tree當前行的高亮顯示樣式
highlight-current:是否高亮當前選中節點,默認值是 false。
.el-tree-node:focus > .el-tree-node__content { background-color: #000 !important; }
僅限子葉節點顯示勾選(隱藏父節點的勾選按鈕)
.el-tree-node{ .is-leaf + .el-checkbox .el-checkbox__inner{ display: inline-block; } .el-checkbox .el-checkbox__inner{ display: none; } }
代碼:
<el-dialog title="選擇分類" :visible.sync="dialogVisible" width="50%"> <el-tree :data="treeData" :check-on-click-node="false" ref="tree"
show-checkbox :check-strictly="true" default-expand-all node-key="id"
:props="defaultProps" @check-change="treeNodeClick" empty-text="暫無數據">
</el-tree> <span slot="footer" class="dialog-footer"> <el-button type="primary" @click="handleClick">確 定</el-button> <el-button type="primary" class="grey_btn" @click="dialogVisible = false">取 消</el-button> </span> </el-dialog>
變量:
data(){
return {
dialogVisible: false,
treeData: [],
selectList: [],
defaultProps: {
children: 'children',
label: 'name',
disabled: (data) => {
return data.level === 1 || data.level === 2 || data.level === 3
}
},
}
}
單選方法:
methods: {
// tree單選
treeNodeClick (data, checked) {
const node = this.$refs.tree.getNode(data)
const str = []
function filterName (node) {
if (node) {
if (node.parent) {
str.push(node.data.name)
filterName(node.parent)
}
}
}
// 獲取當前選擇的id在數組中的索引
const indexs = this.selectList.indexOf(data.id)
// 如果不存在數組中,並且數組中已經有一個id並且checked為true的時候,代表不能再次選擇。
if (indexs < 0 && this.selectList.length === 1 && checked) {
this.$message({
message: '只能選擇一個區域!',
type: 'error',
showClose: true
})
// 設置已選擇的節點為false 很重要
this.$refs.tree.setChecked(data, false)
} else if (this.selectList.length === 0 && checked) {
// 發現數組為空 並且是已選擇
// 防止數組有值,首先清空,再push
this.selectList = []
this.ruleForm.branch = ''
this.selectList.push(data.id)
filterName(node)
this.ruleForm.branch = str.reverse().join('/')
} else if (indexs >= 0 && this.selectList.length === 1 && !checked) {
// 再次直接進行賦值為空操作
this.selectList = []
this.ruleForm.branch = ''
}
},
}
效果如下:
