父组件 -> 子组件html
props vue
<my-component :date="date"></my-component>
注意:若是子组件定义props名称使用了驼峰命名,则须要在传值时改为 - 分开,由于html对大小写不敏感,例如vuex
<my-component :my-date="date"></my-component>
* 可是在vue单文件组件中貌似是能够使用驼峰写法的框架
子组件 -> 父组件this
子组件中直接修改props值能够成功,可是框架会抛出一个错误,因此不推荐spa
推荐的作法:在父组件中定义一个修改props的方法,而后子组件调用父组件的方法prototype
1. 在子组件中直接调用父组件方法修改props值code
this.$parent.change(new Date())
2. 子组件触发事件,在父组件中捕捉而后执行change方法component
父组件:htm
<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)