本文共 682 字,大约阅读时间需要 2 分钟。
在项目中遇到需要在父路由中调用子路由中的方法,这类似于组件间的通信。在子路由中可以直接通过 this.$parent.xxx 调用父页面中的方法,但反向操作则较为复杂。通过引入 Bus(或 Vue 实例)成功解决了这一问题,下文将详细介绍实现方法。
首先,在项目的 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/