我将我的 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/