Vue组件间通信的六种方式

第一种(props)

使用场景:父子组件通信

如果父组件给子组件传递函数:本质是子组件给父组件传递

如果父组件给子组件传递非函数:本质是父组件给子组件传递

//只接收:
props: ['todos']
//限制类型:
props: {name: String}
//限制类型、限制必要性、指定默认值:
props: {
    name: {
        type: String, 
        required: true,
        default: 'zhangsan'
    }
}

路由的props

书写形式:对象,布尔值(只能接收params参数),函数形式

第二种(自定义事件)

使用场景:子组件给父组件传递数据

在父组件中给子组件绑定自定义事件(事件的回调在父组件中)

// 给Student绑定自定义事件
<Student @atguigu="getStudentName"/>
this.$refs.student.$on('atguigu', this.getStudentName)

// 触发Student组件身上的atguigu事件
this.$emit('atguigu', '回传的数据')

第三种(全局事件总线$bus)

使用场景:万能

Vue.prototype.$bus = this


第四种(pubsub-js)

发布与订阅,(在React种使用较多)

使用场景:万能

第五种(插槽)

使用场景:父子组件通信(向子组件指定位置插入html结构)

默认插槽、具名插槽、作用域插槽

<!--父组件-->
<List :todos="todos">
    <!--定义子组件的结构和外观-->
	<template slot-scope="{todo, $index}">
    	<span :style="{color: todo.isComplete ? 'green' : 'red'}">{{$index}}---{{todo.text}}</span>
    </template>
</List>

<!--子组件-->
<li v-for="(item, index) in todos" :key="index">
	<slot :todo="item" :$index="index"></slot>
</li>

第六种(Vuex)

使用场景:万能


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值