Search code examples
vue.jsvue-component

How to use data from one component in another component vuejs


I'm new to vue and I'm trying to use an array from one component to another but I cannot find how to do it.

In component 1 I have this data that I want to transfer and use in component 2.

   const array = [];

In app.vue I have these 2 components next to eachother.

<template>
  <Component 1/>
  <Component 2 />
</template>

Now how do I get this array from component 1 to component 2?

Thanks in advance!


Solution

  • Vue SFC Playground

    As mentioned in the question's comments you should move your array outside Component1 and share it between the both components.

    But if you strongly want/need/have to keep your array inside Component1 you can share the array through a scoped slot that put in the end of Component1:

    App.vue

    <script setup>
    import Component1 from './Component1.vue';
    import Component2 from './Component2.vue';
    </script>
    
    <template>
      <Component1>
        <template #="{array}">
          <Component2 :array="array" />
        </template>
      </Component1>
    </template>
    

    Component1.vue

    <script setup>
    import {ref, shallowReactive} from 'vue';
    const array = shallowReactive(['item1', 'item2']);
    const itemId = ref(array.length);
    </script>
    
    <template>
      <div>I'm Component1</div>
      <button @click="array.push(`item${++itemId}`)">Add item to list</button>
      <slot v-bind="{array}"/>
    </template>
    
    

    Component2.vue

    <script setup>
    defineProps({
      array:{type:Array, default: []}
    });
    </script>
    <template>
      <div>I'm Component2</div>
      <ul>
        <li v-for="item in array">{{item}}</li>
      </ul>
    </template>