School.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <template>
  2. <div class="school">
  3. <h2>学校名称:{{ name }}</h2>
  4. <h2>学校地址:{{ address }}</h2>
  5. </div>
  6. </template>
  7. <script>
  8. import pubsub from 'pubsub-js'
  9. export default {
  10. name:'School',
  11. props:['getSchoolName'],
  12. data() {
  13. return {
  14. name:'尚硅谷',
  15. address:'北京'
  16. }
  17. },
  18. methods:{
  19. demo(msgName,data){
  20. console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
  21. }
  22. },
  23. mounted(){
  24. // console.log('School',this.x)
  25. // this.$bus.$on('hello',(data) => {
  26. // console.log('我是School组件,收到了数据',data)
  27. // })
  28. // this.pubId = pubsub.subscribe('hello',function(msgName,data){
  29. // console.log(this) //undefined
  30. // // console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
  31. // })
  32. // 换成箭头函数
  33. // this.pubId = pubsub.subscribe('hello',(msgName,data) => {
  34. // console.log(this) //VueComponent
  35. // // console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
  36. // })
  37. // 或者将方法放到methods里面
  38. this.pubId = pubsub.subscribe('hello',this.demo)
  39. },
  40. beforeDestroy(){
  41. // this.$bus.$off('hello')
  42. pubsub.unsubscribe(this.pubId)
  43. }
  44. }
  45. </script>
  46. <style scoped>
  47. .school{
  48. background-color: skyblue;
  49. padding: 5px;
  50. }
  51. </style>