作用
一种组件间通信的方式 适用于任意组件间通信。
安装
安装全局事件总线:在入口文件main.js中,给VM添加$bus,任意组件都可以在原型中调用。
- beforeCreate(){
-
- Vue.prototype.$bus = this
-
- }
组件使用
给全局事件总线,绑定自定义事件getName 谁需要接收数据就再谁绑定。
子组件:UserInfo中:
- this.$bus.$on('getName',(data)=>{
- // console.log("UserInfo接收到数据",data);
- this.shopname = data;
- })
组件销毁之前卸载自定义事件
-
- beforeDestroy() {
- this.$bus.$off('getName')
- }
发送数据
谁需要传递数据,谁就调用自定义事件
子组件:Order中:
- methods: {
- sendName() {
- // 谁需要传递数据,谁就调用自定义事件
- this.$bus.$emit("getName",this.name)
- }
- },
安装
一种组件间通信的方式,适用于任意组件间通信,如今有很多消息订阅与发布的包,在这里只介绍一种,pubsub-js。
安装pubsub:npm i pubsub-js
发布信息
引入: import pubsub from 'pubsub-js'
pubsub.publish('hello','hello-world') hello:发布消息的名称,第二个参数:为发布内容
接收消息
- this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
- console.log(this)
- // console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
- })
每次接收消息的时,会生成一个订阅的ID
取消订阅
- beforeDestroy() {
- // this.$bus.$off('hello')
- pubsub.unsubscribe(this.pubId)
- },
$nextTick
定义:在下次DOM更新循环结束之后执行延迟回调,在修改数据之后使用这个方法,获取更新后的DOM。
- this.$nextTick(function(){
- this.$refs.inputTitle.focus()
- })