简体   繁体   中英

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

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?

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.

  • Vuehas 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 need data from different component just pass it with props.

Or if you need this data in multiple components try Vuex:

https://vuex.vuejs.org/guide/

You can change default to null too and remove type. In my case I had to pass ref from sibling.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM