javascript - Vue Dynamic Layouts 两次安装路由器 View 组件

标签 javascript vue.js layout vue-component vue-router

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

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,
  },
...

一些路由 View 组件

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

长话短说;

如果您使用动态布局设置您的项目,按照在线教程中的任何一个,当您导航到布局与上一页不同的路由时,新的路由器 View 组件将被创建、销毁,然后再次创建。这会导致诸如加倍 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 逻辑分离到单独的路由组中,并避免在使用新布局访问页面时加载组件两次的问题。

关于javascript - Vue Dynamic Layouts 两次安装路由器 View 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946922/

相关文章:

Vue.js 2 日期选择器推荐?

javascript - 使用 Vue 和 Laravel 设置 Themeforest HTML 模板。在 router.push 上加载 JS 文件不起作用

安卓 : selectors for custom listviews

android - 两个复选框,只能选择一个

javascript - 类型错误 : Cannot read property "values" from undefined.(第 9 行,文件 "Code")

javascript - 在 HTML5 应用程序中添加音频/视频通话

javascript - 将地理位置添加到现有的谷歌地图

vue.js - 路由器链接绑定(bind)到 b 卡图像

javascript - fullpage.js normalScrollElements 不向下滚动

python - 使用 django-crispy 组合布局时出错