我认为不可能直接模仿React's ref
.Vue中的ref
属性只是一个字符串,用于在渲染功能期间将子组件引用注册到父对象的$refs
对象.
Here are the links to documentations 100 & 101
所以基本上这是一种逆向逻辑..在Vue中,我们不是将ref传递给子对象,而是将其从子对象传递给父对象.因此,现在不可能创建孙辈引用,这正是您所需要的.
不过也有一些变通办法.
1. Quick dirty and not transparent but technically it would work:
Your 100 component. Template:
<el-form ref="elform">
A parent which uses your 100. Template:
<el-form-responsive ref="form">
Script:
...
mounted () {
this.$refs.form = this.$refs.form.$refs.elform
}
在这之后,this.$refs.form
实际上是指granchild <el-form>
2. This one would be more elaborate, but probably mach better then the first method:
为了使el-form-responsive
组件真正透明,可以将子el-form
组件中的一些方法和属性公开给任何潜在的父组件.比如:
100. Template:
<el-form ref="elform">
Script:
export default {
data: () => ({
whatever: null
}),
mounted () {
this.whatever = this.$refs.elform.whatever
},
methods: {
submit () {
this.$refs.elform.submit()
}
}
}
因此,在一些内部,可以像这样使用父el-form-responsive
:
<el-form-responsive ref="form">
...
mounted () {
const formWhatever = this.$refs.form.whatever // actually `whatever` from `el-form`
this.$refs.form.submit() // eventually calls submit on `el-form`
},