javascript - 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: {}
}
}
}
有人可以告诉正确的方法吗?
解决方案
只需尝试通过以下方式从子组件访问父组件:
this.$parent
或者
this.$el.parent
或在子组件中使用inheritAttrs选项以将属性从父级传递到子级:
const ChildComponent = {
inheritAttrs: true,
name: 'child',
props: {
screen: {
type: HTMLDivElement,
default: {}
}
}
}