"Utilizing Vue 3's composition API to effortlessly pass array props down to numerous child

Looking for a way to pass an array from component A (App.vue) through component B to component C? Here's what I have tried:

// A.vue
<script setup>
import B from "./B.vue";
import { reactive } from "vue";
let arrayData = reactive({ [ "hello", "no" ] })
</script>
<template>
  <B :arr="arrayData" />
</template>

// B.vue
<script setup>
import C from "./C.vue";
const props = defineProps({
  arr: {
    type: Array
  }
})
</script>
<template>
  {{ props.arr[0] }} //this displays "hello"
</template>

However, when I try to pass the same array from B.vue to C.vue using

<C :arr="props.arr" />
and access it in C.vue with {{ props.arr[0] }}, I encounter an error message.

https://i.sstatic.net/os13H.png

Although the code provided above has been simplified for clarity, the error message occurs at the exact line where I try to access the 0th index of the array. It seems like passing the array as a prop is causing the issue. If needed, I can provide a link to the GitHub repository in the comments.

Answer №1

When faced with this particular scenario, the optimal approach is to utilize the provide/inject method to transmit data from the grandparent component to the grandchild component:

// A.vue
<script setup>
import B from "./B.vue";
import { reactive,provide } from "vue";
let arrayData = reactive({ [ "hello", "no" ] })
provide('arr',arrayData):
</script>
<template>
  <B />
</template>

Within component C:

// C.vue
<script setup>

import { inject } from "vue";

const arr = inject('arr'):
</script

Answer №2

Ensure that in B.vue, you are passing props correctly as :arr="arr" and not as :arr="props.arr"

<script setup>
import C from "./C.vue";
const props = defineProps({
  arr: {
    type: Array
  }
})
</script>
<template>
  <C :arr="arr" />
</template>

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

How should white space be managed in Bootstrap 4 cards when incorporating responsive column classes - wrap elements inside divs or apply classes directly?

In Bootstrap 4, when applying a responsive column class like "col-sm-8" directly to a "div" with the class "card", whitespace is added between the card border and content. This can be seen in the highlighted yellow area in the image below. https://i.sstat ...

How to pass variables in AngularJS

When displaying data in a grid, I need to change the button icon on click of the active or inactive button. The functionality is working well, but I am having trouble finding the clicked active button to change its icon. In jQuery, we can use "this", but ...

invoking a function in javascript from react

Currently, I am grappling with the task of invoking a JavaScript function from within React while adapting a "React" based "Menu" onto some existing jQuery functions. Below you can find my code for the menu: class Menus extends React.Component{ co ...

What is the best way to identify a specific list item from a dropdown menu and determine its position on

Check out my jsfiddle for reference. My goal is to calculate scores based on different options selected, specifically relating to radiation types. I'm struggling with assigning a score to each type of radiation and integrating the drop-down menu selec ...

Using Vuetify to display icons within a V-data-table component

Having just started learning Vue and Vuetify, I am facing a challenge with displaying a table containing some data. My goal is to have a delete icon in the last column that triggers an action when clicked. However, I am struggling to show the icon while al ...

What is the best way to merge multiple chunks of arrays into a single array

What I currently possess: let json = { key1: 'value1', key2: 'value2', key3: { title: 'yeah' } } let path = ['key3', 'title']; My goal is to concatenate segments of the 'path' array ...

Adjusting the size of an HTML5 canvas using a class function when a resize event occurs

I'm attempting to adjust the size of a canvas element using a resizeCanvas() method triggered by a resize event. When I directly call the method, the canvas resizes without any issues. However, when the event handler triggers subsequent calls, I encou ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

Is it possible to inject JavaScript into the DOM after it has been loaded using an AJAX call?

I have a specific div element identified by the id #id1 that contains clickable links. Upon clicking on these links, an AJAX call is made to retrieve additional links from the server. My current approach involves replacing the existing links within #id1 w ...

There is no way to avoid a PHP variable being displayed in a JavaScript alert box

It may sound silly, but I've spent hours trying to escape this PHP variable that contains post data: $post=array ( 'offers' => '90', 'pn' => '2', 'ord' => 'price', 'category_s ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

Crafting callback functions

My jQuery code looks like this: $('#current_image').fadeOut(function(){ $('#current_image').attr('src',newImage).show(); }); This process is wonderful - the nested function runs smoothly after the fadeOut. I ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Tips for accessing another page when location.state is missing

In my react application, I am passing state through react router and accessing it in the target component/page using the location object. Everything works perfectly fine initially, but when I close the tab and try to open the same page by pasting the URL i ...

I encounter difficulties using my static resources in the root route of my Express.js application

Can you guide me on how to implement styles and images from the assets folder in my webpage, specifically for the root route? As an example, I have a styles.css file located at assets/styles.css. In my code, I am using app.use(express.static('assets&a ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Tips for displaying HTML elements using JSON data in React?

My goal is to dynamically render HTML elements based on JSON data using a React class that takes objects and generates a list of divs. The values inside the divs correspond to the first value in each object within the JSON. Here's an example of the J ...

I am interested in adding a label to a particular vue chart

https://i.sstatic.net/P99u0.png I have successfully added labels to a vue pie chart using the vue-chartjs and chartjs-plugin-labels module. However, the labels show up on all charts when I want them to only appear on a specific chart. Is there a way to ac ...