效果图
router/index.js
import Vue from "vue";
import VueRouter from "vue-router";
// import Home from "../views/Home.vue";
// import My from "../views/My.vue";
// import News from "../views/news.vue";
// import HomeNews from "../components/HomeNews.vue";
// import HomeMsg from "../components/HomeMsg.vue";
// 路由懒加载的写法
const Home = () => import ("../views/Home.vue");
const HomeMsg = () => import ("../views/HomeMsg.vue");
const HomeNew = () => import ("../views/HomeNew.vue");
const About = () => import ("../views/About.vue");
const News = () => import ("../views/News.vue");
const My = () => import ("../views/My.vue");
Vue.use(VueRouter);
/*解决当前导航点击两次回报错*/
// 没有生效
// const routerPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
// return routerPush.call(this, location).catch(error=> error)
// }
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
};
const routes = [
{
path: "",
redirect: "/home",
},
{
path: "/home",
name: "Home",
component: Home,
meta: {
title: "首页",
},
children: [
{
path:'',
redirect:'HomeNew'
},
{
path: "HomeNew",
name: "HomeNew",
component: HomeNew,
meta: {
title: "新闻",
},
},
{
path: "HomeMsg",
name: "HomeMsg",
component: HomeMsg,
meta: {
title: "消息",
},
},
],
},
{
path: "/about",
name: "About",
component:About,
// component: () =>
// import(/* webpackChunkName: "about" */ "../views/About.vue"),
meta: {
title: "关于",
},
},
{
path: "/my",
name: "My",
component: My,
meta: {
title: "我的",
},
},
{
path: "/news",
name: "News",
component: News,
meta: {
title: "新闻",
},
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
linkActiveClass:'active'
});
// 全局前置守卫,设置页面标题
router.beforeEach((to, from, next) => {
// to and from are both route objects. must call `next`.
// document.title = to.meta.title;
document.title = to.matched[0].meta.title;
// console.log(to);
next();
});
export default router;
注意: 嵌套路由中以“/”开头的嵌套路径会被当作根路径,所以子路由上不用加“/”;在生成路由时,主路由上的path会被自动添加到子路由之前,所以子路由上的path不用在重新声明主路由上的path了
。