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

What methods can I use to modify strings within JSX?

Within a JSX file, I am faced with the task of manipulating a particular string in a specific manner: Imagine that I have the following string assigned to medical_specialty = "Plastic Surgery" The objective is as follows: medical_specialty.replace(&apos ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...

What could be causing the Babel installation to fail within Electron? Is Babel necessary for my project or can it be avoided?

Having trouble using the npm package https://www.npmjs.com/package/swipe-detect and encountering the following error message: export default function(target, callback, threshold=150) { ^^^^^^ SyntaxError: Unexpected token export at Module._compile (i ...

Another project cannot import the library that was constructed

I am in the process of creating a library that acts as a wrapper for a soap API. The layout of the library is structured like this: |-node_modules | |-src | |-soapWrapperLibrary.ts | |-soapLibraryClient.ts | |-types | |-soapResponseType.d.ts The libra ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

How to align the navbar toggle button and list items to the right in Bootstrap 5

I'm struggling with a simple html page that has a fixed navbar at the top. Everything looks great when viewed in full-screen mode, with centered links. However, when the page size is reduced, it collapses to a toggle button on the left side. What I re ...

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Instructions for extracting and storing values from a JSON response into an array

Utilizing react-select async feature to fetch options from an input provided via an API. The JSON response contains a list with a "FullName" field, which I aim to extract and store in an array to be used as options. Within the JSON structure, there is a l ...

Angular ng-repeat not populating the list properly, causing a collapse not to display

Currently, I am working on developing an app using Angular.js and Bootstrap UI, but I have run into a problem with a collapse navigation feature. The issue I am facing is that I have an ng-repeat that should be functioning properly. However, when I click ...

Tips for retrieving the MenuItem name upon click event using Menu and MenuItem components in Material UI React

Utilizing MaterialUI's Menu and MenuItem components in a React project, I am looking to display the name of the menu item upon clicking on it. Upon inspecting event.currentTarget in console.log, it returns the entire list item: ListItem Image attache ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

Angular 2: Enhancing Textareas with Emoji Insertion

I am looking to incorporate emojis into my text messages. <textarea class="msgarea" * [(ngModel)]="msg" name="message-to-send" id="message-to-send" placeholder="Type your message" rows="3"></textarea> After entering the text, I want the emoj ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

Warning: An unexpected issue occurred due to an invalid integer being entered as Not a Number (NaN

I've encountered an issue trying to pass data into the "amount" parameter. From the client, I'm sending the "price" to the server successfully. Upon checking the console output, I see the correct information is being received. The typeof check ...