vue.js路由

1. 基础配置

首先需要安装vue-router:

npm install vue-router@4

基础路由配置示例:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

2. 路由模式

Hash模式

import { createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

History模式

import { createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes
})

3. 动态路由匹配

const routes = [
  // 动态路径参数以冒号开始
  { 
    path: '/user/:id', 
    component: User,
    // 可以配置多个参数
    // path: '/user/:id/:type'
  }
]

在组件中获取参数:

<template>
  <div>
    <h1>用户ID: {{ $route.params.id }}</h1>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()
console.log(route.params.id)
</script>

4. 嵌套路由

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      {
        // 当 /user/profile 匹配成功
        path: 'profile',
        component: UserProfile
      },
      {
        // 当 /user/posts 匹配成功
        path: 'posts',
        component: UserPosts
      }
    ]
  }
]

5. 编程式导航

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

// 字符串路径
router.push('/home')

// 带参数的对象
router.push({ 
  path: '/user', 
  query: { 
    userId: '123' 
  }
})

// 命名的路由
router.push({ 
  name: 'user', 
  params: { 
    userId: '123' 
  }
})

// 前进/后退
router.go(1)   // 前进一步
router.go(-1)  // 后退一步
router.back()  // 后退
router.forward() // 前进
</script>

6. 路由守卫

全局前置守卫

router.beforeEach((to, from, next) => {
  // 检查用户是否已登录
  const isAuthenticated = localStorage.getItem('token')
  
  if (to.name !== 'Login' && !isAuthenticated) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

路由独享守卫

const routes = [
  {
    path: '/admin',
    component: Admin,
    beforeEnter: (to, from, next) => {
      // 检查用户权限
      if (hasAdminRights()) {
        next()
      } else {
        next('/403')
      }
    }
  }
]

组件内守卫

<script setup>
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

// 离开路由前
onBeforeRouteLeave((to, from) => {
  const answer = window.confirm('确定要离开吗?未保存的数据将丢失')
  if (!answer) return false
})

// 路由更新前
onBeforeRouteUpdate((to, from) => {
  // 在当前路由改变,但是组件被复用时调用
})
</script>

7. 路由懒加载

const routes = [
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/user',
    name: 'User',
    // 带注释的chunk名称
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue')
  }
]


vue.js路由
http://localhost:8090//archives/vue.jslu-you
作者
潘显镇
发布于
2024年11月25日
许可协议