我正在尝试将 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 中加载的子组件的实例?
对此的任何帮助将非常感激。