Vue $refs 为什么无法获取组件对象

<el-tree ref="permissions_tree" class="permissions-tree" :data="permissions" :props="basicConfig.defaultProps" show-checkbox node-key="id" :render-content="renderNode"></el-tree>
mounted () {
  console.log(this.$refs.permissions_tree);
}

在 mounted 中打印输出的是undefined!这是为什么?

我在表格中渲染的按钮,第一次点击调用 console.log(this.$refs.permissions_tree);得到的也是 undefined,第二次就能正常获取到组件了

{
    title: '操作',
    key: 'action',
    align: 'center',
    render: (h, params) => {
      return h('div', [
        h('Button', {
          props: {
            type: 'primary',
            size: 'small'
          },
          style: {
            marginRight: '5px'
          },
          on: {
            click: () => {
              this.userForm.staffid = params.row.staffid;
              this.userForm.name = params.row.name;
              this.userForm.phoneticize = params.row.phoneticize;
              this.userForm.gender = params.row.gender;
              this.userForm.mobile = params.row.mobile;
              this.userForm.telephone = params.row.telephone;
              this.userForm.identification = params.row.identification;
              this.userForm.positions = params.row.positions;
              this.userForm.permissions = params.row.permissions;
              this.userFormShow = true;
              console.log(this.$refs.permissions_tree); //这里
            }
          }
        }, '编辑')
      ]);
    }
}

图片描述

阅读 27.4k
6 个回答

可能你用v-if来切换组件展示,所以要在下一个tick才能获取到

this.$nextTick(() => {
    console.log(this.$refs.permissions_tree);
});

写在

this.$nextTick(() => {})

里试一下

外层组件是不是使用了v-if,换成v-show 试一下

调用这个方法
this.$nextTick(function () {

    // 里面打印
  })

关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。

我的情况是
<el-dialog :visible.sync="visible">
<子组件 ref="子组件"/>
</el-dialog>

visible没有切换为true时,获取不到$ref.子组件,切换为true后,再在后边一行的this.$nextTick(function () {中,才能获取到

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题