今日在做电商后台管理系统时,我从后端查出来的数据,遍历后赋值给我绑定 key 值的数组,但是发现个问题,没有实时更新过来.
欢迎访问我的博客
My Blog: https://coderblue.cn/
Github:https://github.com/CoderBleu
My Project:https://coderblue.cn/project/
<!-- 树形控件 -->
<el-tree
ref="treeRef"
:data="rightsList"
:props="treeProps"
show-checkbox
default-expand-all
node-key="id"
:default-checked-keys="defaultKeys"
@node-click="handleNodeClick"
></el-tree>
data()中的属性
// 所有权限的数据
rightsList: [],
// 树型控件的属性绑定对象
treeProps: {
label: 'authName',
children: 'children'
},
// 默认选中的节点id值
defaultKeys: []
进展:
我发现设置@node-click="handleNodeClick"事件后,点击节点,新的数据就被渲染出来了,但是这还达不到我的要求,我需要直接打开对话框就显示正常的数据。
handleNodeClick(data, node) {
// 这样可以拿到树组件的 tree对象
const tree = this.$refs.treeRef
this.$refs.treeRef.setCheckedKeys(this.defaultKeys)
console.log(node)
}
这样后我打开对话框,只需要点击下节点就能实时更新数据过来,但即便这样体验感也不好。
最终解决:设置了个延时函数,加个nextTick钩子
我的理解是:
这是因为this.dialogVisible = true时并没有立即更新dom,而是等整个逻辑执行完后再一次新渲染,
因此此时的弹框并未渲染,在dom树中是不存在的,
this. r e f s . t r e e i s u n d e f i n e d 的 所 以 s e t C h e c k e d K e y s 肯 定 也 是 u n d e f i n e d 。 解 决 方 法 : t h i s . refs.tree is undefined的所以setCheckedKeys肯定也是undefined。 解决方法: this. refs.treeisundefined的所以setCheckedKeys肯定也是undefined。解决方法:this.nextTick(),this.$nextTick()会在dom更新之后在执行回调
// 展示分配权限的对话框
showSetRightDialog(id) {
this.getPowerTree(id)
// 设置个延时函数,不然不能实时更新数据
setTimeout(() => {
this.setRightDialogVisible = true
this.$nextTick(function() {
this.$refs.treeRef.setCheckedKeys(this.defaultKeys)
})
}, 300)
},
效果展示: