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. 预览

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

相关推荐
光影少年6 分钟前
对typescript开发框架的理解?
前端·javascript·typescript
We་ct6 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
Wect16 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·typescript
漫游的渔夫1 天前
前端开发者做多步 Agent:别让 AI 边想边乱跑,用 Plan-Act-Observe 稳住 4 步任务
前端·人工智能·typescript
Elastic 中国社区官方博客1 天前
用于 JavaScript 和 TypeScript 的 ES|QL 查询构建器:流式、类型安全的查询构建
大数据·javascript·数据库·elasticsearch·搜索引擎·typescript·全文检索
小爬的老粉丝1 天前
把 Office 预览搬进浏览器:一次仍在继续的纯前端长跑
前端·typescript·docx·ppt·doc·pptx·office预览
Wect2 天前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
漫游的渔夫2 天前
前端开发者做 Agent:别写成一次请求,用 5 步受控循环防止 AI 乱跑
前端·人工智能·typescript
垦利不2 天前
TS基础篇
开发语言·前端·typescript
涵涵(互关)2 天前
GoView各项目文件中的相关语法3
前端·vue.js·typescript