[Vuejs]-Provide a ref to inject it in a child component with Vue js

1👍

Generally the interaction between parent and child component should be done using props and emitted events :

<template>
  <div />
</template>

<script>
export default {
 
  methods:{
      changeParentStyle(){
            this.$emit('change-style')
       }
  }
}
</script>

</style>

parent :

<template>
  <child @change-style="changeStyle" />
</template>

<script>
export default {
  name: 'SearchContainer',
   methods:{
      changeStyle(){
          //change the property that affects your style
       }
   }
}
</script>

</style>

1👍

I have manage to achieve providing ref to children. But in my opinion if you want to communicate betwwen parent and children I think you have got your answer already by Boussadjra Brahim.

Still providing ref has its own use cases. I am usinig it for dialogs.

Here is my solution:

<!-- Parent Component -->

<template>
    <div ref="myRef"></div>
  </template>
  
<script>
  export default {
    name: 'SearchContainer',
    methods:{
        getMyRef(){
            return this.$refs.myRef
        }
    },
    provide() {
      return{
        parentRef: this.getMyRef
    }
    }
  }
</script>


<!-- Child Component -->

<template>
    <div></div>
</template>

<script>
  export default {
    name: 'SearchContainer',
    methods:{
        useRef(){
            this.parentRef().data // Can access data properties
            this.parentRef().method() // can access methods
        }
    }
    inject: ['parentRef']
  }
</script>

Leave a comment