我有一个组件,可以把一切都传给子元素.我已经成功地通过了$attrs分和$listeners分:

<template>
  <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition">
    <slot />
  </el-form>
</template>

但我不确定如何转发$refs,就像我们在React中所做的那样,这样在使用我的组件时:

<el-form-responsive
  class="form"
  :model="formValues"
  status-icon
  :rules="rules"
  ref="form"
  label-width="auto"
  @submit.native.prevent="submitForm"
>

那么this.$refs.form实际上是指子元素<el-form>.

我宁愿透明地这样做,就像你把完全相同的props 传给el-form-responsive,就像你把props 传给el-form一样,而不需要知道refs必须以一种特殊的方式传递.

推荐答案

我认为不可能直接模仿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`  
},

Vue.js相关问答推荐

通过另一个文件调用模块化窗口组件

如何使用 async/await 在 vue js 中添加标头

更改 Vuetify 轮播高度

将 Vue 应用程序挂载到主 Vue 应用程序的容器中

实现登录命令并访问 vuex 存储

运行vue-cli-service build --watch时没有 CSS 文件

使用数组元素的计算(computed)属性

如何只查看数组中的一个对象?

在按键 vuejs 中只允许数字和一个小数点后 2 位限制

可以同时使用 Tailwind css 和 Bootstrap 4 吗?

Keycloak:用户基于角色的客户端登录访问限制

如何在nuxt路由中添加meta?

将 VueJS 数据属性重置为初始值

使用 nuxt,如何将路由名称放在页面标题中?

如何从 vue-apollo 中访问 this.$route?

在路由更改之前显示确认对话框

将 SignalR 与 Vue.js 和 Vuex 集成

如何在 vue.js 2 上循环对象观察者?

如何在布局中使用组件?

如何在 VeeValidate 中自定义错误信息(字段名称)?