javascript Vue - 如何将父引用作为道具传递给孩子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51668630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue - How to pass parent ref to child as a prop?
提问by Tushar Arora
I am trying to pass current component's ref to a child component like this:
我正在尝试将当前组件的 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>
Since Vue.js types don't support HTMLDivElement, I am getting an error in child component when I define screenRefas a prop.
由于 Vue.js 类型不支持HTMLDivElement,当我定义screenRef为 prop时,我在子组件中收到错误。
const ChildComponent = {
name: 'child',
props: {
screen: {
type: HTMLDivElement,
default: {}
}
}
}
Could someone please tell the correct way to do this?
有人可以告诉正确的方法来做到这一点吗?
回答by Andrii
Just try to access parent from child component via:
只需尝试通过以下方式从子组件访问父组件:
this.$parent
or
或者
this.$el.parent
or use inheritAttrsoption in child component for nontransparent pass of attributes from parent to child:
或者在子组件中使用inheritAttrs选项来实现从父级到子级的非透明属性传递:
const ChildComponent = {
inheritAttrs: true,
name: 'child',
props: {
screen: {
type: HTMLDivElement,
default: {}
}
}
}
回答by Valentine Shi
You do all the things correct. Just do not declare the required typefor the screenprop in the child component. The following props: {screen: {default: {}}}will do the trick.
你做的所有事情都是正确的。只是不要在子组件中声明所需type的screen道具。以下props: {screen: {default: {}}}将解决问题。
As side notes:
作为旁注:
The
mountedhook isthe correct place to assign the$refselements to$dataitems as the former is not defined atcreatedhook.Vue has
type: objectthat still would work well for yourscreenprop type validation if you want to apply the props type validation.If you by chance would want to assign the
defaultobject value other than the empty{}you have to assign it via function (unlike non-object data types):default: function () { return {a: 1, b: 2} }
该
mounted挂钩是分配的正确的地方$refs元素$data,因为前者没有在规定的项目created挂钩。Vue公司有
type: object仍然会为您的工作以及screen道具类型的验证,如果你想申请的道具类型验证。如果您偶然想要分配
default空对象以外的对象值,则{}必须通过函数分配它(与非对象数据类型不同):default: function () { return {a: 1, b: 2} }
回答by Canor
If you need data from different component just pass it with props.
如果您需要来自不同组件的数据,只需使用 props 传递即可。
Or if you need this data in multiple components try Vuex:
或者,如果您需要在多个组件中使用此数据,请尝试使用 Vuex:

