美文网首页
09.事件总线的实例

09.事件总线的实例

作者: 小二的学习日记 | 来源:发表于2020-07-07 15:43 被阅读0次

    1.我们先写一个事件总线的实例

    //===>src/views/bus/index.js
    import Vue from 'vue'
    var bus = new Vue();
    
    export default bus;
    

    2.在App.vue中,监听事件
    导入bus组件,在beforeMount()生命周期函数中,用bus.$on()来监听事件,修改isShow属性的状态

    //===>src/App.vue
    <template>
      <div>
        <tabbar v-show="isShow" />
        <!-- 路由容器 -->
        <section>
          <router-view></router-view>
        </section>
      </div>
    </template>
    
    <script>
    import navbar from "./components/Navbar";
    import sidebar from "./components/Sidebar";
    import tabbar from "@/components/Tabbar";
    import bus from "@/bus";
    export default {
      data() {
        return {
          datalist: [],
          isShow: true
        };
      },
      methods: {
        handleAdd() {
          this.datalist.push(this.$refs.mytext.value);
        }
      },
      beforeMount() {
        bus.$on("maizuo", data => {
          // console.log("被通知了maizuo");
          this.isShow = data;
        });
      },
      mounted() {
      
      },
      components: {
        navbar: navbar,
        sidebar: sidebar,
        tabbar
      }
    };
    </script>
    
    <style lang="scss">
    * {
      margin: 0;
      padding: 0;
    }
    html {
      height: 100%;
    }
    li {
      list-style: none;
    }
    </style>
    

    3.在Detail.vue页面,触发事件
    导入bus组件,利用bus.$emit()方法触发事件,在beforeMount()生命周期中,设置隐藏下面的tabbar;在beforeDestroy()生命周期中,设置显示下面的tabbar

    //===>src/views/Detail.vue
    <template>
      ...
    </template>
    <script>
    import axios from "axios";
    import swiper from "@/views/Detail/DetailSwiper";
    import bus from "@/bus";
    export default {
      data() {
        return {
          filminfo: null
        };
      },
      props: ["id"],
      beforeMount() {
        bus.$emit("maizuo", false);
      },
      mounted() {
        ...
      },
      beforeDestroy() {
        bus.$emit("maizuo", true);
      },
      components: {
        swiper
      }
    };
    </script>
    
    <style lang="scss" scoped>
    .poster {
      width: 100%;
    }
    </style>
    
    效果图(下面的导航栏 不见了)

    相关文章

      网友评论

          本文标题:09.事件总线的实例

          本文链接:https://www.haomeiwen.com/subject/mgoaqktx.html