23_全局事件总线&消息订阅与发布

23_全局事件总线

任意组件间通信

在这里插入图片描述

main.js

new Vue({
  render: h => h(App),
  beforeCreate(){
    Vue.prototype.$bus=this //安装全局事件总线
  }
}).$mount('#app')

School.vue

<template>
   <div class="demo">
       <h2>学校名称:{{schoolName}}</h2>
        <h2>学校地址: {{address}}</h2>
   </div>
</template>

<script>
  export default{
      name:'School', 
      data() {
        return {
          schoolName: "尚硅谷",
          address: "北京",
        };
      },
      mounted(){
        this.$bus.$on('hello',(data)=>{
          console.log('我是school组件,收到了数据',data);
        })
      },
      beforeDestroy(){
        this.$bus.$off('hello')
      }
    };
   
</script>


<style>
    .demo{
        background-color: orange;
    }
</style>

student.vue

<template>
  <div>
    <h2>学生名称:{{ name }}</h2>
    <h2>学生年龄: {{ age }}</h2>
    <button @click="senStudentName">把学生名给school组件</button>
  </div>
</template>

<script>
export default {
  name: "Student", //变量 一般和文件名一样
  data() {
    return {
      name: "张三",
      age: 18,
    };
  },
  mounted(){
    // console.log(this.x);
  },
  methods:{
    senStudentName(){
      this.$bus.$emit('hello',666)
    }
  }
};
</script>

<style></style>

消息订阅与发布

在这里插入图片描述

School.vue 订阅消息

<template>
   <div class="demo">
       <h2>学校名称:{{schoolName}}</h2>
        <h2>学校地址: {{address}}</h2>
   </div>
</template>

<script>
import pubsub from 'pubsub-js'
  export default{
      name:'School', 
      data() {
        return {
          schoolName: "尚硅谷",
          address: "北京",
        };
      },
      mounted(){
        // this.$bus.$on('hello',(data)=>{
        //   console.log('我是school组件,收到了数据',data);
        // })
       this.pubId= pubsub.subscribe('hello',function(msgName,data){
          console.log("有人发布了hello消息",msgName,data);
        })
      },
      beforeDestroy(){
        // this.$bus.$off('hello')
        pubsub.unsubscribe(this.pubId)
      }
    };
   
</script>


<style>
    .demo{
        background-color: orange;
    }
</style>

Student.vue 发布消息

<template>
  <div>
    <h2>学生名称:{{ name }}</h2>
    <h2>学生年龄: {{ age }}</h2>
    <button @click="senStudentName">把学生名给school组件</button>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
  name: "Student", //变量 一般和文件名一样
  data() {
    return {
      name: "张三",
      age: 18,
    };
  },
  mounted(){
  },
  methods:{
    senStudentName(){
    //  console.log( this.$bus);
    pubsub.publish('hello',666)
      
    }
  }
};
</script>

<style></style>

$nextTick

在这里插入图片描述

this.$nextTick(function{
	this.$refs.inputTitle.focus()
})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值