Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure:

parent -> child -> secondChild

Currently, there is a variable called isActive in the parent component. Below is how it can be implemented:

parent.vue

<child :active="isActive" />

child.vue

<template>
<secondChild :active="props.active">
</template>


<script setup>

const props = defineProps(['active'])

</script>
secondChild.vue

<template>
{{isActive}}
</template>


<script setup>

const props = defineProps(['active'])

</script>

While this method works, it may not be optimal when dealing with multiple nested components. Any suggestions on achieving this without relying on pinia or vuex?

Appreciate any guidance.

Answer №1

To implement this functionality, you can utilize the provide/inject feature in Vue:

Learn more about provide/inject here

parent.vue

<script setup>
import {provide} from 'vue';

provide('activeStatus', isActive);
</script>

<template>
<childComponent />
</template>
childComponent.vue

<template>
<grandChildComponent />
</template>

grandChildComponent.vue


<template>
<grandChildComponent />
</template>


<script setup>

import {inject} from 'vue';

const isActive = inject('activeStatus', ref(false));

</script>

Answer №2

If you want to create your own implementation of Vue 3 State Management, you can do so by creating a new file.

// stores/customState.js

import { ref } from 'vue'

export const customState = ref(false)

Once you have defined this custom state, you can import it into any component and utilize it as follows. Keep in mind that using ref ensures reactivity across all components...and other options like reactive or computed are also available:

// component.vue

<script setup>
import { customState} from '/stores/customState'

// customState.value is reactive
</script>

<template>
 <!-- Custom state is reactive -->
 {{ customState }}
</template>

While this method works well, it's worth mentioning that if you anticipate sharing this state among multiple components (10 or more), utilizing a library like Pinia would be the recommended approach.

Answer №3

It appears to me that incorporating React's Context API could be beneficial in order to avoid prop drilling. Consider utilizing the Provide/Inject feature instead. By importing provide from vue and implementing it in your parent component to define the data, then using inject to pass that data down to your child component. The structure of your parent component might resemble this:

<template>
  <Provide>
    <div>
      <ChildComponent />
      <div>
         <AnotherChildComponent />
      </div>
    </div>
  </ProvideUserSettings>
</template>

This way, within each ChildComponent, you can include additional components that require access to that data.

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

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

submission of form data and automatic redirection to another page

Seeking advice on managing form submissions and page redirection. I have a landing page with a basic form, where users select criteria and are then redirected to page2 displaying tabular data and query information. When submitting the form on Page1, data ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

What causes the variable to be invisible in the imported file?

Within the main.js file, there is a specific code snippet: var test_mysql = require('./test_mysql.js') ... //additional code before(function(){ test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL ...

Utilizing Express-Partials in conjunction with a single layout to incorporate multiple partials

Recently, as I migrated to Node.js and ExpressJS 3.0, I noticed that partials were no longer supported. However, I stumbled upon express-partials which provided a similar feature. Upon exploring the example on their GitHub page, I came across this snippet ...

Is there a way in jQuery Validation to apply a rule to the entire form rather than just individual elements within the form?

I am facing an issue with a form where each element has its own custom rules that work perfectly. However, the form cannot be submitted unless values are provided for at least one of its elements. It seems like this is a rule for the entire form rather th ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Error Encountered in NextJS - Hydration Unsuccessful

Currently, I am utilizing NextLink in my project to generate links. However, it appears that using NextLink is causing the following error: Hydration failed because the initial UI does not match what was rendered on the server. Upon inspecting the console ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

Executing a JavaScript function within Python using Selenium: A beginner's guide

Within my JavaScript, there is a function called 'checkdata(code)' which requires an argument named 'code' to execute and returns a 15-character string. I recently discovered how to call functions without arguments in JavaScript. Howev ...

pnpm may not be able to resolve dependencies

When I have my package.json file and install all dependencies with npm i, everything works fine. However, when I use pnpm i, I encounter an exception: TypeError: Cannot read property 'uid' of undefined. I don't actually use this library, so ...

Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed. I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it inde ...

What is the process for obtaining the source code for children in React?

Can React extract the source code from children props? Imagine having a component with the following structure... <SomeComp> <Heading>I want to access this code inside the Heading tag</Heading> </SomeComp> How can I retrieve t ...

Order of execution behavior

I am currently working on a function that, when triggered, will populate the webpage with dynamic tiles. These tiles retrieve data from a remote database through an AJAX request and utilize jQuery 3.0 in the implementation. Function Implementation: funct ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Adjusting the timeout for a particular operation according to its unique identifier

I am looking for a solution to call a method that posts an answer after an input change in my Angular project. I want to reset the timeout if another input change occurs to avoid multiple posts. Is there a smart way to achieve this? My project involves po ...