20190130问 Vue组件间如何通信?
- 首先搞清楚组件中的几种通信模式
- 父向子级传递
- 子向父级传递
- 兄弟级传递
- 传递的方式
props传递
代码示例:
// parent
<template>
<child :content="content">
</template>
// child
props: {
content: String
}
$attrs, $listeners
listeners 属性像两个收纳箱,一个负责收纳属性,一个负责收纳事件(不包含props声明过,以及内置特性绑定属性,如class,style等...)
代码示例:
// parent
<template>
<child :content="content" :bar="bar" @one="one" @two="two" class="child" style="width:1rem">
</template>
// child
props: {
content: String,
one: Function
}
console.log(this.$attrs, this.$listeners)
// bar, two
$emit, $on
代码理解:
vm.$on('JS', function say(val) {
// 执行事件并接收回传的参数
console.log('JS, ' + 每日一题)
})
vm.$emit('JS', '每日一题')
// 触发当前实例上的事件
provide,inject主要为高阶组件及组件库所用,理解为允许一个祖先组件为其所有子孙组件注入依赖
代码理解:
// parent
<template>
<child />
</template>
provide: {
name: 'JS',
value:'每日一题',
},
// child
inject: {
name: String,
value: String
}
console.log(this.name, this.value) // JS,每日一题
EventBus思路就是声明一个全局Vue实例变量 EventBus , 把所有的通信数据,事件监听都存储到这个变量上
代码理解:
// Global
let EventBus = new Vue()
// parent
EventBus.$on('received', function (val) {
console.log('received: '+ val)
// received: JS每日一题
})
// child
EventBus.$emit('received', 'JS每日一题')
Vuex
Vuex解决大型项目复杂通信问题,这块这里不做讲解