当前位置:首页 > VUE

vue实现路由管理

2026-01-16 03:17:55VUE

Vue 路由管理实现方法

Vue 路由管理通常通过 vue-router 库实现,以下是具体实现方式:

安装 vue-router

通过 npm 或 yarn 安装最新版本:

npm install vue-router@4
# 或
yarn add vue-router@4

基本路由配置

在项目中创建路由配置文件(通常为 router/index.js):

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(process.env.BASE_URL),
  routes
})

export default router

路由视图渲染

在主入口文件(如 main.js)中引入路由:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

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

在根组件模板中添加 <router-view>

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

导航实现

使用 <router-link> 组件进行导航:

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>

编程式导航:

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

// 带查询参数
router.push({ path: '/about', query: { id: 1 } })

// 命名路由
router.push({ name: 'About' })

动态路由匹配

通过冒号 : 定义动态路径参数:

{
  path: '/user/:id',
  component: User
}

获取路由参数:

import { useRoute } from 'vue-router'

const route = useRoute()
console.log(route.params.id)

路由守卫

全局前置守卫:

router.beforeEach((to, from, next) => {
  // 验证逻辑
  next()
})

组件内守卫:

import { onBeforeRouteLeave } from 'vue-router'

onBeforeRouteLeave((to, from) => {
  // 离开确认逻辑
})

嵌套路由

定义子路由:

{
  path: '/parent',
  component: Parent,
  children: [
    { path: 'child', component: Child }
  ]
}

父组件模板中需要包含 <router-view>

<template>
  <div>
    <h2>Parent Component</h2>
    <router-view/>
  </div>
</template>

路由懒加载

使用动态导入实现组件懒加载:

{
  path: '/lazy',
  component: () => import('../views/Lazy.vue')
}

路由元信息

定义路由元字段:

{
  path: '/admin',
  component: Admin,
  meta: { requiresAuth: true }
}

在导航守卫中访问:

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !isAuthenticated) {
    return '/login'
  }
})

vue实现路由管理

标签: 路由vue
分享给朋友:

相关文章

vue实现tab切换

vue实现tab切换

Vue实现Tab切换的方法 使用v-if和v-show指令 通过v-if或v-show控制不同tab内容的显示与隐藏。v-if会销毁和重建DOM,适合切换频率低的场景;v-show仅切换CSS的dis…

前端多线程实现vue

前端多线程实现vue

前端多线程与Vue的结合 在Vue中实现多线程通常通过Web Worker技术完成。Web Worker允许在后台线程中运行脚本,避免阻塞主线程,适合处理计算密集型任务。 使用Web Worker的…

课程表vue实现

课程表vue实现

实现课程表的Vue组件 创建课程表需要设计数据结构、布局和交互逻辑。以下是一个基于Vue 3的实现方案: 数据结构设计 const timetableData = ref([ { ti…

vue实现导航切换内容

vue实现导航切换内容

Vue实现导航切换内容的方法 在Vue中实现导航切换内容,可以通过以下方式实现: 使用动态组件 动态组件通过<component :is="currentComponent">实现内容…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成…