vue事件总线

//事件总线: 类似于单独对于一个功能的处理。组件间通信的方式;适用于任意组件间通信
// export default{
//     //监控事件
//     $on(eventName,handler){
//         if(!listeners[eventName]){
//             listeners[eventName] = new Set();
//         }
//         listeners[eventName].add(handler);
//     },
//     //取消监听
//     $off(eventName,handler){
//         if(!listeners[eventName]){
//             return
//         }
//         listeners[eventName].delete(handler);
//     },
//     //触发事件
//     $emit(eventName,...args){
//         if(!listeners[eventName]){
//             return
//         }
//         for(const handler of listeners[eventName]){
//             handler(...args)
//         }
//     }
// }

//事件总线还有这种写法,这个vue实例上也有on,off,emit
/*
 * 事件名:mainScroll
 * 含义:主区域滚动条位置变化后触发
 * 参数:
 * - 滚动的dom元素,如果是undefined,则表示dom元素已经不存在
 *
 * 事件名:setMainScroll
 * 含义:当需要设置主区域滚动条位置时触发
 * 参数:
 * - 滚动高度
 */

import Vue from "vue";
const app = new Vue({})
Vue.prototype.$bus = app;
export default app;

  在组件中使用方式:

<template>
  <div class="to-top-container" v-show="show" @click="handleClick">
    Top
  </div>
</template>

<script>
export default {
    data(){
        return{
            show:false,
        }
    },
    created(){
        this.$bus.$on('mainScroll',this.handleScroll)
    },
    destroyed(){
        this.$bus.$off('mainScroll',this.handleScroll)
    },
    methods:{
        handleScroll(dom){
            if(!dom){
                this.show = false;
                return;
            }
            this.show = dom.scrollTop >= 500;
        },
        handleClick(){
            this.$bus.$emit('setMainScroll',0)
        }
    },
}
</script>

<style scoped lang="less">
@import '@/styles/var.less';
    .to-top-container{
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background:@primary;
        position: fixed;
        z-index: 99;
        right: 50px;
        bottom: 50px;
        cursor: pointer;
        line-height: 50px;
        color: #fff;
        text-align: center;
    }
</style>

  

posted on 2023-06-14 09:04  爱前端的小魏  阅读(74)  评论(0编辑  收藏  举报

导航