如何在vuejs的另一个组件中使用一个组件的数据

问题描述 投票:0回答:1

我是 vue 新手,我正在尝试使用从一个组件到另一个组件的数组,但我找不到如何操作。

在组件 1 中,我想要在组件 2 中传输和使用这些数据。

   const array = [];

在 app.vue 中,我有这两个相邻的组件。

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

现在如何将该数组从组件 1 获取到组件 2?

提前致谢!

vue.js vue-component
1个回答
0
投票

Vue SFC 游乐场

正如问题评论中提到的,您应该将数组移到外部

Component1
并在两个组件之间共享它。

但是,如果您强烈希望/需要/必须将数组保留在内部

Component1
,您可以通过作用域插槽共享数组:

应用程序.vue

<script setup>
import Component1 from './Component1.vue';
import Component2 from './Component2.vue';
</script>

<template>
  <Component1>
    <template #="{array}">
      <Component2 :array="array" />
    </template>
  </Component1>
</template>

组件1.vue

<script setup>
const array = ['item1', 'item2'];
</script>

<template>
  <div>I'm Component1</div>
  <slot v-bind="{array}"/>
</template>

组件2.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>
© www.soinside.com 2019 - 2024. All rights reserved.