组件通信常用方式
prop 、eventbus(事件总线)、vuex
自定义事件 (不常用)
1、边界情况:$parent 、$children、$root、$ref、provide/inject
2、非prop特性:$attrs、$listeners
组件间通信:
// 父传给子
// child
props: {msg :String}
// parent
<component msg='hello world!'>
// 子传给父
// child
this.$emit('eventName', params)
// parent
<component @eventName="eventName($event)">
2、事件总线
任意两个组件之间传递值常用事件总线或者是vuex的方式
Vue使用事件总线的方法
// 项目中引入在main.js中
import VueBus from 'vue-bus'
Vue.use(VueBus)
// 使用
this.$bus.emit('reAdd', params)
this.$bus.on('reAdd')
实现原理:
// 事件派发、监听和回调管理
class Bus{
constructor(){
this.callbacks = {}
}
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit(name, args){
if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args))
}
}
}
// main.js
vue.prototype.$bus = new Bus()
// 使用
this.$bus.emit('reAdd', params)
this.$bus.on('reAdd')
创建唯一的全局数据管理管理者store,通过它管理数据并通知组件状态变更
4、$parent/$root
兄弟组件之间通信可通过共同祖辈搭桥,$parent或$root
// brother1
this.$parent.$on('funcName',(msg)=>{})
// brother2
this.$parent.$emit('funcName', 'hello world!')
5、$children
父组件可以通过$children访问子组件实现父子组件通信(缺点:不能保证子元素顺序)
// 子组件中有一个方法
handleClose() {
}
// 父组件中方法
clickHandle(){
this.$children[0].handleClose()
}
6、$attrs/$listeners
包含了父作用于中不作为prop被识别(且获取)的特性绑定(class和style除外),当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class和style除外),并且可以通过v-bind="$attrs"传入内部组件
// 子组件 msg没有在props中声明
<span>{{$attrs.msg}}</span>
// 父组件
<component msg="hello world!"/>
// 子组件 点击按钮会调父组件的handleClick方法
<button v-on="$listeners">按钮</button>
// 父组件
<component @click="handleClick"/>
7、refs
获取子节点引用
// 子组件
submitForm(){
}
// 父组件
<search-form ref="form"/>
this.$refs.form.submitForm()
8、provide/inject
能够实现祖先和后代之间的传值
// 祖先
provide(){
return {
msg: 'hello world'
}
}
// 后代
inject:[ 'msg' ]