## 组件通信 ### 1.props (父子组件通信) ### 2.自定义事件(父子组件通信) 1. ref ``` 父组件 template标签中 ref="名称" mounted() this.$refs.aaa.$on("自定义的方法名",传送的方法) ``` 子组件 this.$emit("自定义的方法名") 2. ``` 在父组件中 绑定点击事件 @/v-on:click 绑定好事件方法 在子组件中 通过this.$emit("监听事件",传参) $on 绑定事件 $emit 监听事件 $off 解绑事件 ``` ### 3.全局事件总线(任意组件通信) ``` new Vue({ render: h => h(App), beforeCreate(){ Vue.prototype.$bus = this } }).$mount('#app') ``` $on/$emit/$off this.$bus.$on 使用在mounted声明周期中 this.$bus.$off 使用在beforeDestroy声明周期中 ### 4.消息的发布订阅(任意组件通信) npm install pubsub-js 使用页面 import pubsub from 'pubsub-js'; 发布消息 pubsub.subscribe() 订阅消息 pubsub.publish() 如果调用方法有传参 所传真实传参在第二个位置 详情请见Demo5.vue 取消订阅 pubsub.unsubscribe()