【问题标题】:Vue 3 - Get access to router-view instance in order to call child methodsVue 3 - 访问路由器视图实例以调用子方法
【发布时间】:2021-07-07 06:33:03
【问题描述】:

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

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

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

[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!

在花了很多时间之后,我还没有找到合适的方法来访问我的 &lt;router-view/&gt; 中加载的子实例以触发我在其中托管的方法。

[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 访问在路由器视图中加载的子组件实例?

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: vue.js vue-router vuejs3 vue-router4


    【解决方案1】:

    Vue Router 4 的 &lt;router-view&gt;v-slot prop 中公开渲染的视图组件,可以使用 &lt;component&gt; 渲染,您可以对其应用模板参考:

    <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

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2021-08-25
      • 1970-01-01
      • 2017-03-06
      • 2019-10-28
      • 2012-12-19
      • 2017-05-29
      • 1970-01-01
      • 2015-12-23
      相关资源
      最近更新 更多