自学内容网 自学内容网

vue2 src_消息订阅和发布(pubsub-js)

main.js

//引入Vue
import Vue from "vue";
//引入App
import App from './App';

//关闭Vue的生产提示
Vue.config.productionTip = false;

new Vue({
    el:'#app',
    render: h => h(App),
});

App.vue

<template>
   <div class="app">
      <h1>{{ msg }}</h1>
      <School/>
      <Student/>
   </div>
</template>

<script>
import Student from "@/components/Student";
import School from "@/components/School";
export default {
  name: "App",
  components: {
    School,
    Student,
  },
  data() {
    return {
      msg: 'helloこんにちは',
      studentName: ''
    }
  }
}
</script>

<style>
   /*
   全局的样式是不需要加scoped
   全局共享
   */
   .app{
     background: gray;
     padding: 5px;
   }
</style>


Student.vue

<template>
   <div class="student">
     <h2>姓名:{{  name }}</h2>
     <h2>性别: {{ sex }}</h2>
     <button @click="sendStudentName">把学生名传递给school组件</button>
   </div>
</template>

<script>
import pubsub from "pubsub-js";
export default {
  name: "Student",
  data(){
    console.log(this);
    return {
       name: '张三',
       sex: '男',
    }
  },
  methods:{
    sendStudentName(){
      // this.$bus.$emit('hello', this.name);
      //发布消息
      pubsub.publish('hello', this.name);
    }
  },
}
</script>

<style scoped>
  .student{
    background: orange;
    padding: 5px;
    margin-bottom: 10px;
  }
</style>

School.vue

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

<script>
import pubsub from 'pubsub-js';
export default {
  name: "School",
  data(){
    console.log(this);
    return {
       name: 'wust university',
       address: '武汉科技大学'
    }
  },
  mounted() {
    // console.log('School', this);
    // this.$bus.$on('hello', (data) => {
    //   console.log(`我是School组件,我收到了数据,${data}`);
    // })
    //订阅消息 隔空对讲机喊话
    this.pubId = pubsub.subscribe('hello',  (name, msg) => {
      //注意这里写剪头函数this才不会丢
      console.log(`有人发布了hello消息,回调被执行,data: ${msg}`);

    });
  },
  beforeDestroy() {
    // this.$bus.$off('hello'); //销毁解绑
    //取消订阅
    pubsub.unsubscribe(this.pubId); //取消订阅
  }
}
</script>

<style scoped>
   /*scoped代表局部的*/
  .demo{
    background: skyblue;
    padding:5px
  }
</style>



原文地址:https://blog.csdn.net/weixin_46742102/article/details/143966154

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!