Vue 3 - 访问路由器视图实例以调用子方法

2024-02-20

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

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

我的 Vue 2 应用程序按照以下建议运行得非常好这个帖子 https://forum.vuejs.org/t/get-instance-of-router-view/2610 :

[Vue 2] 应用程序.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] 路由器.js

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

在 Vue 2 中,我可以使用以下方法访问 router-view 实例:this.$refs.routerView

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

花了很多时间后,我还没有找到正确的方法来访问我的子实例加载到我的 <router-view/>为了触发其中托管的我的方法。

[Vue 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 访问在 router-view 中加载的子组件的实例?

对此的任何帮助将非常感激。


Vue 路由器 4<router-view>在 a 中公开渲染的视图组件v-slot prop https://next.router.vuejs.org/api/#router-view-s-v-slot可以用以下方式渲染<component>,您可以对其应用模板引用:

<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 https://codesandbox.io/s/access-router-views-rendered-view-component-s3lmv?file=/src/App.vue

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue 3 - 访问路由器视图实例以调用子方法 的相关文章

随机推荐