Vue Dynamic Layouts 两次安装路由器视图组件

Vue Dynamic Layouts mounting router-view component twice

我将我的 Vue 项目设置为使用动态布局 - 即,页面之间持续存在的布局,假设新页面的布局与上一页的布局相同。我的问题是,当我转到具有不同布局的路线时,router-link 组件被创建和销毁,然后再次创建,这给我带来了一些问题。我的设置如下:

App.vue

<template>
  <component :is="layout">
    <router-view :layout.sync="layout" />
  </component>
</template>

<script>
import LayoutPortal from '@/layouts/LayoutPortal';
import LayoutOffline from '@/layouts/LayoutOffline';
import LayoutDefault from '@/layouts/LayoutDefault';

export default {
  name: 'App',

  components: {
    LayoutPortal,
    LayoutOffline,
    LayoutDefault,
  },
...

一些路由视图组件

<template>
...
</template>

<script>
import LayoutDefault from '@/layouts/LayoutDefault';

export default {
    ...

    created() {
        this.$emit('update:layout', LayoutDefault);
    },
}
</script>

布局默认

<template>
  <div class="wrapper">
    <slot />
  </div>
</template>

<script>
export default {
  name: 'layout-default',
};
</script>

tldr;

如果您使用动态布局设置您的项目,遵循许多在线教程中的任何一个,当您导航到布局与上一页不同的路由时,新的路由器视图组件将被创建、销毁,然后再次创建。这会导致诸如加倍 mounted() 调用等问题。

我最终选择了嵌套(子)路线(https://router.vuejs.org/guide/essentials/nested-routes.html):

{
      path: '/portal',
      component: LayoutPortal,
      beforeEnter(to, from, next) {
        if (!store.getters.auth) {
          next('/login');
          return;
        }

        next();
      },
      children: [
        {
          path: 'home',
          name: 'portal-home',
          component: PortalHome,
        },
        {
          path: 'about',
          name: 'portal-about',
          component: PortalAbout,
        },
        ...

通过这种方式,我可以将布局加载为父路由,将 beforeEnter 逻辑分离到单独的路由组中,并避免使用新布局的页面加载组件两次的问题。