博客
关于我
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/

你可能感兴趣的文章
tableviewcell 中使用autolayout自适应高度
查看>>
Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
order by rand()
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
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
查看>>