Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example:

The Parent component provides the ref:

<template>
  <div ref="myRef" />
</template>

<script>
export default {
  name: 'SearchContainer',
  provide: {
    parentRef: this.$refs.myRef
  }
}
</script>

</style>

And the Child component injects it:

<template>
  <div />
</template>

<script>
export default {
  name: 'SearchCard',
  inject: ['parentRef']
}
</script>

</style>

Answer №1

Typically, the communication between a parent and child component is best achieved through the use of props and emitted events:

<template>
  <div />
</template>

<script>
export default {
 
  methods:{
      adjustParentLayout(){
            this.$emit('adjust-layout')
       }
  }
}
</script>

</style>

parent :

<template>
  <child @adjust-layout="modifyLayout" />
</template>

<script>
export default {
  name: 'DisplayContainer',
   methods:{
      modifyLayout(){
          //make changes to the style-related properties
       }
   }
}
</script>

</style>

Answer №2

Successfully implemented the process of providing refs to children. However, if there is a need for communication between parent and children components, Boussadjra Brahim's solution is highly recommended.

Despite that, using refs still has its own set of practical applications. Personally, I find it useful especially when dealing with dialogs.

Below is my approach:

<!-- 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Vue - Ways to securely integrate Firebase config data into main.js

Currently, I am utilizing firebase within a Vue application with the following configuration: var firebaseConfig = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", appId: "", measurementId: " }; ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Attempting to implement a multi-select input field using AJAX

I am attempting to save multi-select input using ajax in a Laravel application, but I keep encountering the following error: {message: "Function name must be a string", exception: "Error", …} Below is my Blade code: <select class= ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

Simultaneous Vue components

Here's an example of a string: "Greetings Earthlings! I come in peace." Along with a set of words. ["Greetings", "Earthlings", "peace"] I want to automate the process of enclosing matching words within Vue components. For instance, it should look ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Is it possible to restrict the application of jquery .css() to a particular media query only?

Whenever a user's browser width is below 1160px, a media query is set up to hide my website's right sidebar. They can bring it back by clicking on an arrow icon, causing it to overlap the content with absolute positioning. To achieve this functi ...

In node.js, what is the syntax for invoking a function within a struct from that same function?

Here is a brief overview of my code: exports.entity = { name: "Foo", //Etc... start: function () { this.attack(); }, attack: function () { setTimeout(attack, 1000); //Doesn't work ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

Encountering a Django Channels issue while loading the JavaScript wrapper

After successfully running the server, the following appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...