灏天阁

vue3.2/Vite/Ts17: 模板路由配置

· Yin灏

安装 vue-router

pnpm install vue-router

搭建路由前端页面

  • 创建路由组件文件夹:src / views
|-- src
     |-- views
           |-- 404
                 |-- index.vue
           |-- home
                 |-- index.vue
           |-- login
                 |-- index.vue

配置路由

  • 创建文件夹:src / router
|-- src
     |-- router
           |-- index.ts
           |-- routes.ts
// src / router / routes.ts
export const constantRoute = [
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
    name: "login", // 命名路由
  },
  {
    path: "/",
    component: () => import("@/views/home/index.vue"),
    name: "layout",
  },
  {
    path: "/404",
    component: () => import("@/views/404/index.vue"),
    name: "404",
  },
  {
    path: "/:pathMatch(.*)*",
    redirect: "/404",
    name: "Any",
  },
];
// src / router / index.ts
import { createRouter, createWebHashHistory } from "vue-router";
import { constantRoute } from "./routes";
//...
let router = createRouter({
  history: createWebHashHistory(), // 路由模式 hash 模式
  routes: constantRoute,
  // 路由切换的时候,页面的水平和垂直方向自动滚动到起始位置
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});
export default router;
//...

入口文件注册路由

// main.ts
//...
import router from "./router";
//...
app.use(router);

定义路由出口

<!-- App.vue -->
<template>
  <div>
    <router-view></router-view>
  </div>
</template>
``

- Book Lists -