Category

How to use nested arrays in props in Vue 3?

A

Administrator

by admin , in category: Discussion , 5 months ago

In Vue 3, you can pass nested arrays as props to child components just like you would with any other data type. Here's a basic example of how you can define a component with a nested array prop and use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// ParentComponent.vue
<template>
  <div>
    <ChildComponent :nestedArrayProp="nestedArray"></ChildComponent>
  </div>
</template>


<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';


export default {
  components: {
    ChildComponent
  },
  setup() {
    // Define a nested array
    const nestedArray = ref([
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]);


    return {
      nestedArray
    };
  }
};
</script>


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ChildComponent.vue
<template>
  <div>
    <ul>
      <li v-for="(innerArray, index) in nestedArrayProp" :key="index">
        <ul>
          <li v-for="(item, innerIndex) in innerArray" :key="innerIndex">{{ item }}</li>
        </ul>
      </li>
    </ul>
  </div>
</template>


<script>
export default {
  props: {
    nestedArrayProp: {
      type: Array,
      required: true
    }
  }
};
</script>


In this example:

  • The parent component (ParentComponent.vue) defines a nested array nestedArray and passes it as a prop to the child component (ChildComponent.vue).
  • The child component receives the prop nestedArrayProp and iterates over it to display the nested arrays.

You can adjust the structure and content of the nested array according to your specific use case.

no answers