VUE 3-访问路由器视图实例以调用子方法 [英] Vue 3 - Get access to router-view instance in order to call child methods

查看:46
本文介绍了VUE 3-访问路由器视图实例以调用子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Vue 2.x应用程序迁移到Vue 3.x。 不幸的是,在过去的两天里,我一直在努力寻找这个简单问题的有效解决方案:

我的应用程序用于移动设备,在屏幕顶部,我有一个顶部栏,左右各有两个上下文按钮。这些按钮触发与My<router-view/>中加载并承载在其中的视图相关的方法。

我的Vue 2应用按照this post的建议运行良好:

[Vue 2]App.vue

<template>
    <app-bar>
        <bar-btn @click="$refs.routerView[$route.meta.leftBtn.methodName]($route.meta.leftBtn.arguments)">Left btn</bar-btn>
        <div>View title</div>
        <bar-btn @click="$refs.routerView[$route.meta.rightBtn.methodName]($route.meta.rightBtn.arguments)">Right btn</bar-btn>
    </app-bar>
    <main>
        <router-view ref="routerView"/>
    </main>
</template>

存储在我的路由的元数据中的方法名称和可选参数:

[Vue 2]Router.js

{
    name: 'View 1',
    path: '/',
    component: MyView1,
    meta: {
        requiresAuth: false,
        leftBtn:  { methodName: 'showLeftDialog',  arguments: 'myArgument' }
        rightBtn: { methodName: 'showRightDialog', arguments: 'myArgument' }
    },
},

在Vue 2中,我使用以下命令访问路由器视图实例:this.$refs.routerView

遗憾的是,它不再适用于Vue 3!

花了很长时间之后,我还没有找到适当的方法来访问 <router-view/>中加载的子实例,以便触发其中承载的方法。

[版本3]这不起作用:

Does not work:
this.$refs.routerView[this.$route.meta.leftBtn.methodName](this.$route.meta.leftBtn.arguments)

Does not work:
this.$router.currentRoute.value.matched[0].components.default.methods[this.$route.meta.leftBtn.methodName](this.$route.meta.leftBtn.arguments)

Does not work:
this.$refs.routerView.$refs    => this is an empty object

简单地说,如何使用Vue 3访问路由器视图中加载的子组件实例?

如有任何帮助,我们将不胜感激。

推荐答案

Vue Router 4的<router-view>在可以使用<component>呈现的v-slot prop中公开呈现的视图组件,您可以对其应用模板ref:

<router-view v-slot="{ Component }">
  <component ref="view" :is="Component" />
</router-view>

则可以通过$refs.view.$.ctx

访问组件的方法
<bar-btn @click="$refs.view.$.ctx[$route.meta.leftBtn.methodName]($route.meta.leftBtn.arguments)">Left btn</bar-btn>
<bar-btn @click="$refs.view.$.ctx[$route.meta.rightBtn.methodName]($route.meta.rightBtn.arguments)">Right btn</bar-btn>

demo

这篇关于VUE 3-访问路由器视图实例以调用子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆