鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ vue 中 eventbus 的問題

vue 中 eventbus 的問題

vue 項(xiàng)目有兩個(gè)組件:hello 組件、apple 組件,這兩個(gè)組件是兄弟組件,想實(shí)現(xiàn)的效果是 hello 組件里的數(shù) num 隨機(jī)增加之后,apple 組件的 num 也共享這個(gè)狀態(tài),同時(shí)增加。

所以,在全局寫了一個(gè) eventbus,然后在 hello 組件里點(diǎn)擊增加按鈕的時(shí)候會(huì)發(fā)送一個(gè) ‘a(chǎn)dd’ 事件,把這個(gè) num 發(fā)送出去,然后在 apple 組件監(jiān)聽這個(gè) ‘a(chǎn)dd’ 事件。

寫完之后,在 hello 組件里面引入 apple 組件,然后注冊(cè),然后寫在 template 里,打開瀏覽器,訪問 hello 組件,點(diǎn)擊增加按鈕,apple 組件會(huì)同時(shí)更新狀態(tài),沒有問題。

現(xiàn)在問題來了,我先在 hello 組件點(diǎn)擊增加按鈕,發(fā)送 ‘a(chǎn)dd’ 之后,然后跳轉(zhuǎn)到 apple 組件頁面,發(fā)現(xiàn) num 沒有變,這是為什么?這應(yīng)該不是跨域問題把?

hello 組件代碼:

<template>
  <div>
    <h1>hello組件</h1> {{ num }}
    <button @click="handleAdd">隨機(jī)增加</button>
    <router-link to="/apple">to apple</router-link>
    <Apple></Apple>
  </div>
</template>
<script>
import Apple from './Apple'
export default {
  components: { Apple },
  data () {
    return { num: 0 }
  },
  methods: {
    handleAdd () {
      this.num = Math.floor(Math.random() * 100 + 1)
      this.$bus.emit('add', this.num)
    }
  }
}
</script>

apple 組件代碼:

<template>
  <div>
    <h1>apple組件</h1> {{ num }}
  </div>
</template>

<script>
export default {
  data () {
    return { num: 0 }
  },
  created () {
    this.$bus.on('add', val => {this.num = val})
  }
}
</script>

bus 代碼:

const install = function (Vue) {
  const Bus = new Vue({
    methods: {
      emit (event, ...args) {
        this.$emit(event, ...args)
      },
      on (event, callback) {
        this.$on(event, callback)
      },
      off (event, callback) {
        this.$off(event, callback)
      }
    }
  })
  Vue.prototype.$bus = Bus
}

export default install

回答
編輯回答
焚音

1.看到你說的是頁面跳轉(zhuǎn)了,在跳轉(zhuǎn)之前發(fā)送事件,這個(gè)時(shí)候apple組件還不在內(nèi)存里,所以接收不到數(shù)據(jù),跳轉(zhuǎn)之后hello組件的生命周期結(jié)束,也不在生命周期里了
2.eventbus只能在都掛載在內(nèi)存里的組件之間傳遞數(shù)據(jù),像你這種需求可以用vuex,或者在路由之間傳遞數(shù)據(jù)

2017年9月9日 00:17
編輯回答
喜歡你

我記得可以這樣。你實(shí)驗(yàn)一下。
用一個(gè)bus(vue實(shí)例)做收發(fā)中心,而不只是用來綁定事件。
類似于這樣

const Bus = new Vue({
    data () {
        return {
            key1:'',
            key2: ''
        }
    },
    created () {
        this.$on('event1', val => {
            this.key1 = val
        }),
        this.$on('event2', val => {
            this.key2 = val
        })
    }
  })
  Vue.prototype.$bus = Bus
}

各個(gè)組件觸發(fā)還用

import bus from 'bus',
bus.$emit(xxxx)

獲取的時(shí)候不用$on,使用計(jì)算屬性來獲取bus的值

import bus from 'bus'
computed: {
    key () {
        return bus.key1
    }
}

寫了個(gè)demo,確實(shí)可以,為了保證bus一直都在,可以把它添加到到Vue上
https://jsfiddle.net/8hyL912o/

2017年5月20日 23:38
編輯回答
糖豆豆

請(qǐng)問如果是這樣 那怎么解決

2017年3月27日 20:41