Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - How to pass parent ref to child as a prop?

Tags:

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?

like image 519
Tushar Arora Avatar asked Aug 03 '18 08:08

Tushar Arora


People also ask

How do I pass props from parent to child at Vue?

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.


2 Answers

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: {}
    }
  }
}
like image 108
Andrii Avatar answered Sep 21 '22 00:09

Andrii


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}
    }
    
like image 28
Valentine Shi Avatar answered Sep 20 '22 00:09

Valentine Shi