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

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

相关推荐
零凌林13 小时前
使用exceljs将excel文件转化为html预览最佳实践(完整源码)
前端·html·excel·vue3·最佳实践·文件预览·exceljs
岁岁岁平安2 天前
Vue3学习(组合式API——reactive()和ref()函数详解)
前端·javascript·vue.js·学习·vue3·reactive·ref
三天不学习2 天前
Vue3 本地环境 Vite 与生产环境 Nginx 反向代理配置方法汇总【反向代理篇】
运维·nginx·vue3·vite·反向代理
能来帮帮蒟蒻吗3 天前
VUE3 -综合实践(Mock+Axios+ElementPlus)
前端·javascript·vue.js·笔记·学习·ajax·typescript
菜鸟una3 天前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
struggle20254 天前
continue通过我们的开源 IDE 扩展和模型、规则、提示、文档和其他构建块中心,创建、共享和使用自定义 AI 代码助手
javascript·ide·python·typescript·开源
Bl_a_ck4 天前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
Bl_a_ck4 天前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
菜鸟una5 天前
【layout组件 与 路由镶嵌】vue3 后台管理系统
前端·vue.js·elementui·typescript
小张快跑。5 天前
【Vue3】使用vite创建Vue3工程、Vue3基本语法讲解
前端·前端框架·vue3·vite