You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何在一个组件中使用另一个组件的数据?

Vue兄弟组件数组传递方案

状态提升到父组件(新手首选)

这是处理兄弟组件共享数据最直观的方式,把共享数组放到父组件(App.vue),让Component1负责更新数据,Component2接收数据:

  1. 修改App.vue,定义共享数组和更新方法
<script setup>
import { ref } from 'vue'
import Component1 from './components/Component1.vue'
import Component2 from './components/Component2.vue'

// 共享数组定义在父组件
const sharedArray = ref([])

// 定义修改数组的方法,传给Component1使用
const updateSharedArray = (newData) => {
  // 可根据需求写修改逻辑,比如添加元素、替换数组等
  sharedArray.value.push(newData)
}
</script>

<template>
  <!-- 把更新方法传给Component1 -->
  <Component1 :update-array="updateSharedArray" />
  <!-- 把共享数组传给Component2 -->
  <Component2 :array="sharedArray" />
</template>
  1. Component1中调用方法更新数组
<script setup>
// 接收父组件传来的更新方法
const props = defineProps({
  updateArray: Function
})

// 示例:在操作中更新数组
const addNewItem = () => {
  props.updateArray('新增的元素')
}
</script>
  1. Component2中接收并使用数组
<script setup>
// 接收父组件传来的数组
const props = defineProps({
  array: Array
})
</script>

<template>
  <div>
    从Component1传递来的数组:{{ array }}
  </div>
</template>

其他可选方案

  • 全局状态管理(适合中大型项目):用Pinia(Vue3)或Vuex(Vue2)创建全局状态仓库,把数组存到仓库里,两个组件直接从仓库读取、修改数据,无需父组件中转。
  • 事件总线(不推荐大型项目):创建全局事件中心,Component1触发事件传递数组,Component2监听事件接收数据。但这种方式容易让逻辑分散,后期维护麻烦,Vue3官方已不推荐。

内容的提问来源于stack exchange,提问作者Tibo Mertens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:06:22