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)
使用场景:万能
还没有评论,来说两句吧...