elementUI el-tree setCheckedKeys使用nextTick出现的问题

[Vue warn]: Error in nextTick: "TypeError: Cannot read properties of undefined (reading 'setCheckedKeys')"
TypeError: Cannot read properties of undefined (reading 'setCheckedKeys')
elementUI使用el-tree做数据回显使用setCheckedKeys时报setCheckedKeys为undefined

  1. 确保使用this.$nextTick(()=>{})
    this.$nextTick的作用是修改数据后立刻得到更新的DOM

  2. 确保DOM初始化之后再nextTick
    当el-tree嵌在el-dialog中,或是使用v-if去控制一个块儿的展示时,确保先将DOM初始化后再进行nextTick

<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
  <el-tree ref="menu" 
           node-key="id"
           :data="menuTree" 
           :check-strictly="!form.menuCheckStrictly" 
           :empty-text="$t('system.role.pleaseWait') || '加载中,请稍后'" 
           :props="defaultProps"
           show-checkbox></el-tree>
</el-dialog>
getCheckedMenuByRoleId(roleId).then(res => {
  this.open = true // 正确做法,打开dialog时才会进行DOM初始化
  this.$nextTick(() => {
    this.$refs.menu.setCheckedKeys(res.data)
  })
  // this.open = true // 错误做法,还未进行DOM初始化就进行nextTick
})

前端小白一枚,如有错误请指正~

参考:
https://vue3js.cn/interview/vue/nexttick.html#一、nexttick是什么

posted @ 2023-03-20 11:47  FuKai  阅读(1377)  评论(0编辑  收藏  举报