Element UI 树组件:如何将数组值作为默认选中节点
Element UI 树组件:如何将数组值作为默认选中节点
如果您想在 Element UI 树组件中将数组的值作为默认选中的节点,可以使用 default-checked-keys 属性。该属性接收一个数组,数组中的值将作为树节点的默认选中标识。
示例代码:
<el-tree :data='treeData' show-checkbox default-expand-all :default-checked-keys='treeList'
node-key='resId' highlight-current :props='defaultProps' @node-click='handleClick' />
解释:
:data='treeData':设置树组件的数据源。show-checkbox:显示复选框,允许用户选择节点。default-expand-all:默认展开所有节点。:default-checked-keys='treeList':将treeList数组的值作为默认选中节点。node-key='resId':设置节点的唯一标识符。highlight-current:高亮当前选中的节点。:props='defaultProps':设置树节点的属性,例如label和children。@node-click='handleClick':监听节点点击事件。
注意:
treeList数组中的值必须与树节点的resId属性值匹配。- 如果
treeList数组中的值不存在于树节点中,则不会选中该节点。
示例:
假设 treeList 数组的值为 [1, 3, 5],树节点的数据为:
[
{
"resId": 1,
"label": "节点 1"
},
{
"resId": 2,
"label": "节点 2"
},
{
"resId": 3,
"label": "节点 3"
},
{
"resId": 4,
"label": "节点 4"
},
{
"resId": 5,
"label": "节点 5"
}
]
那么,在树组件中,节点 1、节点 3 和节点 5 将被默认选中。
通过使用 default-checked-keys 属性,您可以轻松地将数组值作为默认选中节点,从而实现动态设置树节点的选中状态。
完整代码示例:
<template>
<div>
<el-tree :data='treeData' show-checkbox default-expand-all :default-checked-keys='treeList'
node-key='resId' highlight-current :props='defaultProps' @node-click='handleClick' />
</div>
</template>
<script>
export default {
data() {
return {
treeData: [
{
"resId": 1,
"label": "节点 1"
},
{
"resId": 2,
"label": "节点 2"
},
{
"resId": 3,
"label": "节点 3"
},
{
"resId": 4,
"label": "节点 4"
},
{
"resId": 5,
"label": "节点 5"
}
],
treeList: [1, 3, 5]
}
},
methods: {
handleClick(data, node) {
// 处理节点点击事件
}
}
}
</script>
希望以上信息对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/pkaT 著作权归作者所有。请勿转载和采集!