Red Fox
Red Fox

Reputation: 67

Try to pass $ref data to prop data of component

I have a component Carousel, and a method:

carousel () {
  return this.$refs.carousel
}

When I try pass to prop of other component, I get undefined in prop data, why?

<Dots :carousel="carousel()" />

In child component I have:

export default {
  name: 'Dots',
  props: ['carousel']
}

In mounted when I try call console.log(this.carousel), I get undefined. But I need get a component data of Carousel. How I can do it?

Sandbox: https://codesandbox.io/s/flamboyant-monad-5bhjz?file=/src/components/Test.vue

Upvotes: 1

Views: 394

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28434

You can set a function in carousel to return the data you want to send to dots. Then, in the parent component, set its return value to an attribute in data which will be passed as a prop:

const dotsComponent = Vue.component('dotsComponent', { 
  template: '#dotsComponent',
  props: ['carousel']
});

const carouselComponent = Vue.component('carouselComponent', { 
  template: '#carouselComponent',
  data() { return { id:1 } },
  methods: { 
    getData() { return { id: this.id } } 
  }
});

new Vue({
  el: "#app",
  components: { dotsComponent, carouselComponent },
  data() { return { carousel:null } },
  mounted() { this.carousel = this.$refs.carousel.getData(); }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div><carousel-component ref="carousel"/></div>
  <div><dots-component :carousel="carousel"/></div>
</div>

<template id="dotsComponent"><p>Dots: {{carousel}}</p></template>

<template id="carouselComponent"><p>Carousel</p></template>

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could pass the ref directly without using a method any other property :

 <Dots :carousel="$refs.carousel" />

Upvotes: 0

Related Questions