Vue - 如何将父引用作为道具传递给孩子?

新手上路,请多包涵

我正在尝试将当前组件的 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 定义为道具时,我在子组件中遇到错误。

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

有人可以告诉正确的方法吗?

原文由 Tushar Arora 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 296
1 个回答

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

 this.$parent

或者

this.$el.parent

或在子组件中使用 inheritAttrs 选项以将属性从父级传递到子级:

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

原文由 Andrii 发布,翻译遵循 CC BY-SA 4.0 许可协议

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