router/index.ts
import {
createRouter,
createWebHistory,
RouteRecordRaw,
createWebHashHistory,
RouteLocationNormalized,
NavigationGuardNext,
} from "vue-router";
import layout from "../views/layout.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "",
redirect: "/home",
component: layout,
children: [
{
path: "/home",
name: "Home",
component: () => import("../views/Home.vue"),
meta: {
title: "首页",
parentpath: "/home",
},
},
{
path: "/login",
name: "login",
component: () => import("../views/login.vue"),
meta: {
title: "登录/注册",
parentpath: "/login",
},
},
],
},
];
//决定路由模式
const isPro: boolean = process.env.NODE_ENV === "prodution";
const router = createRouter({
//history是路由模式(线上线下)
history: isPro
? createWebHashHistory(process.env.BASE_URL)
: createWebHistory(process.env.BASE_URL),
routes,
});
router.beforeEach(
(
to: RouteLocationNormalized,
from: RouteLocationNormalized,
next: NavigationGuardNext
) => {
document.title = to.meta.title;
console.log(from);
next();
}
);
export default router;
main.ts
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
App.vue
<template>
<div id='root'>
<div id='nav'>
<router-link to='/'> Home</router-link>
<router-link to='/contact'>Contact </router-link>
</div>
<router-view />
</div>
</template>