【Vue】组件传值的六种方法

本文详细介绍了Vue中组件间的六种通信方式:1) 父组件通过props向子组件传递数据;2) 子组件通过$emit向父组件发送消息;3) 使用ref属性访问组件实例;4) 利用eventBus实现兄弟组件通信;5) 通过Vuex进行跨组件状态管理;6) 利用attrs和listeners在组件间传递属性和事件。
摘要由CSDN通过智能技术生成

Vue 组件之间的通信大概归类为:

父子组件通信: props/ e m i t ; r e f / r e f s ; emit;ref/refs; emitref/refsattrs / l i s t e n e r s ; listeners; listenersparent / c h i l d r e n 兄 弟 组 件 通 信 : e v e n t B u s ; v u e x 跨 级 通 信 : e v e n t B u s ; V u e x ; children 兄弟组件通信: eventBus;vuex 跨级通信: eventBus;Vuex; children:eventBusvuex:eventBusVuexattrs / l i s t e n e r s 一 、 p r o p s / listeners 一、props/ listenersprops/emit(父子组件通信)
1.父组件向子组件传值
通过 props 传值。
父组件的代码:

<template>
  <div class="section">
    <child :list="list"></child>
  </div>
</template>
<script>
import child from './child.vue'
export default {
   
  components: {
    child },
  data() {
   
    return {
   
      list: ['a1', 'b2', 'c3']
    }
  }
}
</script>

子组件的代码(即 child.vue):

<template>
  <div>
    <span v-for="(item, index) in list" :key="index">{
   {
   item}}</span>
  </div>
</template>
<script>
export default {
   
  props: ['list'],
}
</script>

2.子组件向父组件传值
$emit 绑定一个自定义事件, 当这个语句被执行时, 就会将参数 arg 传递给父组件,父组件通过 v-on 监听并接收参数。

父组件的代码:

<template>
  <div class="section">
    <child :list="list"  @onEmitIndex="onEmitIndex"></child>
    <p>{
   {
   item}} => {
   {
   currentIndex}}</p
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值