博客
关于我
Vue使用bus进行组件间、父子路由间通信
阅读量:374 次
发布时间:2019-03-05

本文共 682 字,大约阅读时间需要 2 分钟。

项目中路由间通信解决方案

在项目中遇到需要在父路由中调用子路由中的方法,这类似于组件间的通信。在子路由中可以直接通过 this.$parent.xxx 调用父页面中的方法,但反向操作则较为复杂。通过引入 Bus(或 Vue 实例)成功解决了这一问题,下文将详细介绍实现方法。

一、引入 Bus 实例

首先,在项目的 src 文件夹下创建 utils 目录,并新建 bus.js 文件:

import Vue from 'vue'const bus = new Vue()export default bus

二、子路由中监听

在子路由中引入 Bus 实例:

import bus from "@/utils/bus"

在子路由的生命周期钩子中(通常使用 mounted 方法)注册监听事件:

mounted() {  // 在父页面使用的方法名称  bus.$on('test', this.test)}

三、父页面触发方法

在父页面中引入 Bus 实例:

import bus from "@/utils/bus"

在需要触发子路由方法的父页面中:

methods: {  createGroup() {    bus.$emit('test')  }}

四、注意事项

由于子路由在 mounted 钩子中注册监听,可能存在多次监听的情况,建议在注册前取消原有的监听:

mounted() {  bus.$off('test') // 取消之前的监听  bus.$on('test', this.test)}

这种方法能够确保事件监听的唯一性,避免多次触发问题。

转载地址:http://vtmg.baihongyu.com/

你可能感兴趣的文章
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.environ 没有设置环境变量
查看>>