I am trying to pass current component's ref to a child component like this:
<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 screenRef
as a prop.
const ChildComponent = {
name: 'child',
props: {
screen: {
type: HTMLDivElement,
default: {}
}
}
}
Could someone please tell the correct way to do this?
The way it works is that you define your data on the parent component and give it a value, then you go to the child component that needs that data and pass the value to a prop attribute so the data becomes a property in the child component. You can use the root component (App.
Just try to access parent from child component via:
this.$parent
or
this.$el.parent
or use inheritAttrs option in child component for nontransparent pass of attributes from parent to child:
const ChildComponent = {
inheritAttrs: true,
name: 'child',
props: {
screen: {
type: HTMLDivElement,
default: {}
}
}
}
You do all the things correct. Just do not declare the required type
for the screen
prop in the child component. The following props: {screen: {default: {}}}
will do the trick.
As side notes:
The mounted
hook is the correct place to assign the $refs
elements to $data
items as the former is not defined at created
hook.
Vue has type: Object
that still would work well for your screen
prop type validation if you want to apply the props type validation.
If you by chance would want to assign the default
object value other than the empty {}
you have to assign it via function (unlike non-object data types):
default: function () {
return {a: 1, b: 2}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With