【问题标题】:Vue - How to pass parent ref to child as a prop?Vue - 如何将父引用作为道具传递给孩子?
【发布时间】:2018-08-03 08:43:32
【问题描述】:

我正在尝试将当前组件的 ref 传递给这样的子组件:

<template>
    <div class="screen" ref="screen">
        <child-component :screenRef="screenRef">
        </child-component>
    </div>
</template>


<script>
    const Parent = {
        name: 'parent',
        data: {
            screenRef: {}
        },
        mounted() {
            this.screenRef = this.$refs['screen']
        }
    }
</script>

由于 Vue.js 类型不支持 HTMLDivElement,当我将 screenRef 定义为 prop 时,子组件中出现错误。

const ChildComponent = {
  name: 'child',
  props: {
    screen: {
      type: HTMLDivElement,
      default: {}
    }
  }
}

有人能告诉我正确的方法吗?

【问题讨论】:

  • this.screenRef = this.$el$el 是组件的根元素。
  • @EricGuan 问题不在于我无法获得ref,而是我无法将其作为道具传递。
  • 你为什么需要这样的东西来描述你想要实现的目标
  • 那你为什么不把这个计算的结果从父母传给孩子呢?
  • 如果你真的需要这种方式,那么传递整个 $refs 对象

标签: javascript vue.js vuejs2


【解决方案1】:

尝试通过以下方式从子组件访问父组件:

this.$parent

this.$el.parent

或在子组件中使用 inheritAttrs 选项以实现从父级到子级的非透明属性传递:

const ChildComponent = {
  inheritAttrs: true,
  name: 'child',
  props: {
    screen: {
      type: HTMLDivElement,
      default: {}
    }
  }
}

【讨论】:

  • inherit 记录在哪里?
  • 你可以在这里找到它的文档012.vuejs.org/api/options.html#inherit 哦,是的,我只是错过了它现在在 v2 中调用 inheritAttrs。见这里:vuejs.org/v2/api/#inheritAttrs
  • inheritAttrsinherit 不一样,默认为true
  • 是的,你是对的inheritAttrsinherit 的情况类似(仅适用于不可识别的属性,但不适用于数据范围)...
【解决方案2】:

你做的所有事情都是正确的。只是不要在子组件中为screen 属性声明所需的type。以下props: {screen: {default: {}}} 可以解决问题。

附注:

  • mounted 挂钩$refs 元素分配给 $data 项目的正确位置,因为前者未在 created 挂钩中定义。

  • 如果您想应用道具类型验证,Vue has type: Object 仍然适用于您的 screen 道具类型验证。

  • 如果您希望分配 default 对象值而不是空的 {},则必须通过函数分配它(与非对象数据类型不同):

    default: function () {
        return {a: 1, b: 2}
    }
    

【讨论】:

    【解决方案3】:

    如果您需要来自不同组件的数据,只需使用 props 传递即可。

    或者,如果您在多个组件中需要这些数据,请尝试使用 Vuex:

    https://vuex.vuejs.org/guide/

    【讨论】:

      【解决方案4】:

      您也可以将默认值更改为 null 并删除类型。就我而言,我必须从兄弟姐妹那里传递 ref。

      const ChildComponent = {
        name: 'child',
        props: {
          screen: {
            default: null
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        • 2023-01-31
        相关资源
        最近更新 更多