Vue 组件通信

父组件 -> 子组件

props 

<my-component :date="date"></my-component>

注意:如果子组件定义props名称使用了驼峰命名,则需要在传值时改成 - 分开,因为html对大小写不敏感,例如

<my-component :my-date="date"></my-component>

* 但是在vue单文件组件中貌似是可以使用驼峰写法的

 

子组件 -> 父组件

子组件中直接修改props值可以成功,但是框架会抛出一个错误,所以不推荐

推荐的做法:在父组件中定义一个修改props的方法,然后子组件调用父组件的方法

1. 在子组件中直接调用父组件方法修改props值

this.$parent.change(new Date())

2. 子组件触发事件,在父组件中捕捉然后执行change方法

父组件:

<my-component :my-date="date" @changeDate="change"></my-component>

子组件:

this.$emit('changeDate', new Date())

推荐使用第二种

 

子组件 -> 子组件

这种情况属于两个不相关的子组件之间的通信,我们无法通过props将两者关联起来,两种解决办法:

1. vuex : 全局状态管理器

2. 事件总线:EventBus

定义:本质上就是实例化一个新的Vue对象,这个对象专门负责处理多组件之间的通信

用法:

// main.js
Vue.prototype.$EventBus = new Vue()

绑定一个eventBus到Vue对象,在页面中通过 on(注册),emit(触发)

//component1
this.$EventBus.$on('change', function(param){
  console.log('事件触发',param)
})
//component2
this.$EventBus.$emit('change', 123)
posted @ 2019-03-31 15:28  吃饭睡觉打豆豆o  阅读(264)  评论(0编辑  收藏  举报