Vue 里怎样在 Render 中使用 $refs

使用的 iView Select 组件,组件有一个方法: clearSingleSelect() . 调用方法为 this.$refs.nameSelect.clearSingleSelect(), 经过测试正常使用是没问题的。现在想要在 render 函数里调用, 一直获取不到 this.$refs.nameSelect ,报 undefined

相关代码

h('Select', {
    ref: 'nameSelect',
    props: {
        transfer: true,
        clearable: true,
    },
    on: {
        'on-change': (value) => {
            if (value === 'CLEAR') {
                this.$refs.nameSelect.clearSingleSelect()
            }
        },
    },
}, this.assembleOptions(h, this.options))

怎样在 Render function 里面使用 $refs 呢?

补充:


this 指向是没问题的,log(this.$refs) 能看到其他直接在 template 里的写好的组件的 ref . 感觉问题应该是当 render 函数把 Select 组件渲染以后,this.$refs 没有动态更新。 所以报 undefined ,有没有手动去更新 this.$refs 的方法,或者直接获取到 render 函数渲染出来的实例的方法?

阅读 20k
12 个回答

你估计用的h是组件返回的 这个是vnode作用域实在 h所在的组件 你可以把h改成 this.$createElement
clipboard.png

clipboard.png

应该是this指向的问题

这种请求一般就几种问题
this指向
nameSelect通过for为数组
异步问题$refs 只会在组件渲染完成之后

感觉是你on里面箭头函数的问题

这里有两个问题.

一个是你这里使用了箭头函数改变了this指向,从运行时变成了定义时。

二是在render里面获取this.$refs这种操作只能获取上次渲染的dom节点,这确定是你想要的效果吗?

你想要在 render 函数里调用, 一直获取不到 this.$refs.nameSelect ,报 undefined,肯定是渲染时机的问题。
render 不要用 this

不要用箭头函数

把完整的代码贴一下,为什么你的描述里还有用template呢?有render为什么还有template?

新手上路,请多包涵

在获取this.$refs时要等render函数返回,所以你应该在this.nextTick函数中获取,我试过是可以的。

为了能继续使用 jsx,这样也是可以的:

h = this.$createElement

return (
  <div>
     <yourElement ref={yourRefName}></yourElement>
  </div>
)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题