Vite4+Typescript+Vue3+Pinia 从零搭建(5) - 路由router

项目代码同步至码云 weiz-vue3-template
Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。

1. 安装

shell 复制代码
npm i vue-router@4

2. 集成

1. 新建两页面进行示例

src/view下新建home.vuelogin.vue,内容如下:

vue 复制代码
<script setup lang="ts">
defineOptions({
  name: 'V-home'
})
</script>

<template>
  <div>home page</div>
</template>

<style lang="scss" scoped></style>

login.vue里修改下对应name即可

2. src下新建router文件夹

index.ts作为路由入口,static.ts作为静态路由,modules内还可以放入其他类型路由,整体目录结构如下:

复制代码
src
|   
+---router
|   |   index.ts
|   +---modules
|       |   static.ts

static.ts内容如下:

ts 复制代码
const routes = [
  {
    path: '/',
    component: () => import('@/views/home.vue')
  },
  {
    path: '/login',
    component: () => import('@/views/login.vue') //路由懒加载
  }
]

export default routes

index.ts内容如下:

ts 复制代码
import { Router, createRouter, createWebHistory } from 'vue-router'

/** 自动导入 src/router/modules 下的静态路由
 * import.meta.glob使用说明:https://cn.vitejs.dev/guide/features#glob-import
 */
const modules: Record<string, any> = import.meta.glob(['./modules/**/*.ts'], {
  eager: true
})

/** 初始路由 **/
const routes: any[] = []

Object.keys(modules).forEach((key) => {
  const module = modules[key].default
  if (Array.isArray(module)) {
    for (const item of module) {
      routes.push(item)
    }
  } else {
    routes.push(module)
  }
})

/**
 * 创建路由实例
 * createRouter选项有:https://router.vuejs.org/zh/api/interfaces/RouterOptions.html
 * hash模式使用createWebHashHistory(): https://router.vuejs.org/zh/api/#Functions-createWebHashHistory
 */
export const router: Router = createRouter({
  history: createWebHistory(),
  routes,
  strict: true,
  scrollBehavior(_to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  }
})

/**
 * 路由守卫
 * https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
 */
router.beforeEach((to, _from, next) => {
  // isAuthenticated 代表你的鉴权
  const isAuthenticated = true
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

export default router

3. 修改App.vue

承载路由,并增加导航

vue 复制代码
<script setup lang="ts"></script>

<template>
  <router-link to="/"> 去首页 </router-link> 丨 <router-link to="/login"> 去登录 </router-link>
  <router-view />
</template>

<style scoped></style>

4. 修改main.ts

使用路由

ts 复制代码
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

import router from '@/router/index'

createApp(App).use(router).mount('#app')

3. 预览

其他用法,包括传参、重定向、动态路由、过渡动效等,请参考官方文档

相关推荐
晓说前端2 小时前
TypeScript 核心语法进阶 —— 字面量类型与类型推论
前端·typescript
布兰妮甜6 小时前
从 0 搭建企业级 Vue3/Vite 脚手架(规范、eslint、husky、打包、环境变量全流程)
typescript·vue3·vite·脚手架·前端工程化
东方小月7 小时前
从0开发一个 Coding Agent(一):前言
前端·人工智能·typescript
gis开发之家1 天前
《Vue3 从入门到大神35篇》Vue3 源码详解(五):effect 依赖收集原理——track 与 trigger 是如何工作的?
javascript·typescript·前端框架·vue3·vue3源码
退休倒计时1 天前
【每日一题】LeetCode 131. 分割回文串 TypeScript
算法·leetcode·typescript
华玥作者2 天前
uniapp 万条数据不卡顿:我写了个虚拟列表组件 hy-list,原生支持瀑布流
数据结构·uni-app·list·vue3
橘子星2 天前
在浏览器里跑大模型!用 WebGPU 零成本部署 DeepSeek-R1
前端·typescript
bonechips2 天前
React + WebGPU:在浏览器里跑一个 DeepSeek 推理模型
react.js·typescript
触底反弹3 天前
🔥 React 零基础入门(上):环境搭建 + JSX 深度解析
前端·react.js·typescript
谷哥的小弟3 天前
TypeScript对象类型
javascript·typescript