嗨,我有两个模板:
Main.vue
404.vue
如果用户进入正常页面,则应使用Main.vue
模板,并且每个页面都有嵌套的路由。
如果用户输入的页面不存在,则应使用带有错误的404.vue
模板。
我尝试了以下操作,但除localhost:8080/
(root路径访问)以外,它始终显示404错误:router.js:
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'main',
component: Main,
childrens: [{
path: '/',
name: 'Home',
components: {
default: () =>
import ('@/views/Home'),
leftInfo: () =>
import ('@/views/DashboardAdditionalInfo'),
rightInfo: () =>
import ('@/components/common/MyTicketsList')
}
},
{
path: 'dashboard',
name: 'Dashboard',
components: {
default: () =>
import ('@/views/Dashboard'),
leftInfo: () =>
import ('@/views/DashboardAdditionalInfo'),
rightInfo: () =>
import ('@/components/common/MyTicketsList')
}
}
]
},
{
path: '*',
name: '404',
component: () =>
import ('@/templates/404.vue')
}
]
})
有关如何处理这种情况的任何想法?当然,我可以将404手柄放在Main路线内,但这将显示两个侧边栏。
答案 0 :(得分:1)
您可以使用shards ui vue template中的动态布局方法。实际上,它会根据您在<router-view/>
中提供路线的可选元标记将应用程序级别router.js
包装在正确的布局组件中。
App.vue:
<template>
<div id="app">
<component :is="layout">
<router-view/>
</component>
</div>
</template>
<script>
export default {
name: 'app',
computed: {
layout() {
// none-layout will be used if the meta.layout tag is not set
// computed may not be best place in vue lifecycle for this but it works ok
return `${this.$route.meta.layout || 'none'}-layout`;
}
}
}
</script>
router.js:
import Vue from "vue";
import Router from "vue-router";
import Errors from "./views/Errors.vue";
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: "/",
name: "dash",
component: () => import('./views/Dashboard.vue'),
meta: { layout: 'default-dash' }
},
{
path: '/signup',
component: () => import('./views/Signup.vue'),
// meta.layout tag not present so 'none' will be used
},
{
path: '*',
component: Errors,
meta: { layout: 'none' }
}
]
});
main.js:
import Vue from 'vue'
import App from './App.vue'
import router from "./router";
// Layouts
import DefaultDash from '@/layouts/DefaultDash.vue';
import None from '@/layouts/None.vue';
// Layouts as usable components
Vue.component('default-dash-layout', DefaultDash);
Vue.component('none-layout', None);
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
DefaultDash.vue:
<template>
<div>
<NavBar/>
<SideBar/>
<slot/>
</div>
</template>
<script>
import NavBar from "../components/NavBar";
import SideBar from "../components/SideBar";
export default {
name: "default-dash",
components: { NavBar, SideBar }
};
</script>
None.vue:
<template>
<div>
<slot/>
</div>
</template>
<script>
export default {
name: "none"
};
</script>
现在,您的vue 404错误将在没有任何侧边栏或导航栏的情况下加载。您可以将所有主要内容页面封装在所需的任何外部布局中,而要做的就是指定要在meta标签中使用的模板。