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>

  

posted @ 2017-12-27 18:25  小虫1  阅读(7383)  评论(0编辑  收藏  举报