Vue消息订阅与发布

1、安装pubsub-js

npm i pubsub-js

2、订阅消息


<script>
import pubsub from 'pubsub-js'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'School',
  data() {
    return {
      studentName: ''
    }
  },
  methods: {
    sendMessage(data) {
      console.log('School组件收到了数据:', data)
      this.studentName = data
    }
  },
  mounted() {
    // this.$bus.$on('getName', data => {
    //   console.log('School 收到了:', data)
    //   this.studentName = data
    // })
    // this.$bus.$on('getName', this.sendMessage)
    this.pubId = pubsub.subscribe('getName', (messageName, data) => {
      // console.log('School接收的了数据:', messageName, data)
      this.studentName = data
    })
  },
  beforeDestroy() {
    //  this.$bus.$off('getName')
    pubsub.unsubscribe(this.pubId)
  }
}
</script>

3、发布消息

<template>
  <div>
    <button @click="sendName">get名字</button>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Student',
  data() {
    return {
      name: '张飞'
    }
  },
  methods: {
    sendName() {
      // this.$bus.$emit('getName', this.name)
      pubsub.publish('getName', this.name)
    }
  }
}
</script>

<style></style>
创作不易 请尊重他人劳动成果,未经授权禁止转载!
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇