skip to Main Content

I need to pass an array from component A (App.vue) through component B to component C. What I do is this (this first step works, just read it to understand):

// 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] }} //works fine, I get "hello"
</template>

But if I do the same thing with the other 2, meaning, I state in B.vue <C :arr="props.arr" /> instead of {{ props.arr[0] }} and I put the same exact props code in C.vue (i.e. const props….) and in C template I call {{ props.arr[0] }}, the problem is I get error message.

enter image description here

Now, my code is not exactly like this, I only changed some names to make it more clear and basic to understand, but that’s that. "Reading ‘0’" is right, since I try to read props.arr[0], but the fact is the error line 33:42 is exactly, in fact, where I try to read that 0 position in the array. It doesn’t work only as a prop. If I state an array in C.vue, it works, but as I said I need to pass the array as a prop from A to C. I don’t know if I can post a link to the repository on gitHub, but in case I can link it in the comments.

2

Answers


  1. In this situation the best solution is to use provide/inject to pass data from grandparent component to grandchild one :

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

    in component C :

    // C.vue
    <script setup>
    
    import { inject } from "vue";
    
    const arr = inject('arr'):
    </script
    
    Login or Signup to reply.
  2. In component B.vue you should pass props :arr="arr" not :arr="props.arr"

    <script setup>
    import C from "./C.vue";
    const props = defineProps({
      arr: {
        type: Array
      }
    })
    </script>
    <template>
      <C :arr="arr" />
    </template>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search