入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Vue之eventBus的简单使用

创建时间:2018-03-06 投稿人: 浏览次数:339

为了解决下拉选项在点击外面的时候可以关闭该下拉选项,使用eventBus

1 在src目录下创建eventBus.js文件

import Vue from "vue"

const eventBus = new Vue()

export { eventBus }

2 在需要点击该区域的标签时关闭该下拉选项的地方设置点击事件,一般为根组件

<div id="app" @click="resetComponent">
resetComponent() {
        eventBus.$emit("reset-component")
      }

在这之前要引入eventBus

import { eventBus } from "../eventBus"

3 在下拉选项存在的组件中设置方法

监听外部的点击事件

mounted() {
      eventBus.$on("reset-component", () => {
        this.isDrop = false
      })
    }

但是这样因为冒泡机制下拉选项在刚刚拉下来的时候就又监听到了reset-component方法,所以要取消冒泡,同时还要保证只有一个下拉选项在下拉状态.

toggleDrop (event) {
        event.stopPropagation()
        eventBus.$on("reset-component", () => {
          this.isDrop = false
        })
        this.isDrop = !this.isDrop
      },



阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像