vue中eventbus 多次觸發的問題


  
相比於react,vue是一個更上手很快的框架。所說簡單易用,但在做Vue項目的過程中,就會發現,坑還是有的。
組件之間傳遞數據是一個常見的需求,父子組件傳遞數據在官網有介紹,除了父子組件,一般地,任意組件之間傳遞數據無非2種方式:
1.vuex
2.eventbus
一般地,小項目中建議用eventbus,具體怎么用呢?
main.js
var bus = new Vue()

// in component A method
bus.$emit('select', 1)

// in component B created hook
bus.$on('select', function (id) {
    console.log('B頁面打印:'+id);//1
})

// in component C created hook
bus.$on('select', function(id){
    console.log('C頁面打印:'+id);//1
})
這樣就沒有問題了嗎?
如果只在B頁面監聽事件,那沒有問題(起碼表現上)。
如果在B,C2組件監聽事件,那就有問題了。只要C組件的頁面打開過,在B組件的頁面觸發事件,C組件頁面的監聽函數也執行了。講道理,C頁面此時已經銷毀了。
我們試一下:先打開C的頁面:

 

接下來,我們打開B的頁面:

這真真讓人迷惑。
vue的作者在git上回答過,解決辦法:
在監聽的B,C組件beforeDestroy()生命周期函數里取消監聽:
beforeDestroy () {
    bus.$off('select',this.handle)
}

 

這時候,匿名函數就不行了。,C組件在監聽的時候,回調函數改成具名函數:
bus.$on('select',this.handle)

  

 

本文的出問題寫法,完整文件:

A.vue

<template>
    <div class="help-page">
        <p @click="click"">A</p>
    </div>
</template>

<script type="text/javascript">
    export default{
        data(){
            return{

            }
        },
        created(){

        },
        methods:{
            click(){
                bus.$emit('select', 1)
            }
        }
    }
</script>
<style lang="less">

</style>

  

B.vue

<template>
    <div class="help-page">
        <A></A>
        <p>B</p>
    </div>
</template>

<script type="text/javascript">
    import A from './A.vue'
    export default{
        data(){
            return{

            }
        },
        created(){
            bus.$on('select', function(id){
                console.log('B頁面打印:'+id);
            })

        },
        components:{
            A
        },
        methods:{

        }
    }
</script>
<style lang="less">

</style>

  

C.vue

<template>
    <div class="help-page">
        <A></A>
        <p>C</p>
    </div>
</template>

<script type="text/javascript">
    import A from './A.vue'
    export default{
        data(){
            return{

            }
        },
        created(){
            bus.$on('select', function(id){
                console.log('C頁面打印:'+id);
            })

        },
        components:{
            A
        },
        methods:{

        }
    }
</script>
<style lang="less">

</style>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM