当前位置:首页 > VUE

vue实现路由导航

2026-01-11 23:16:52VUE

Vue 路由导航的实现

Vue 中实现路由导航通常使用 Vue Router 库。以下是具体实现方法:

安装 Vue Router 在项目中安装 Vue Router 依赖:

npm install vue-router

配置路由 在项目中创建路由配置文件(通常是 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'

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

路由导航方式

声明式导航 在模板中使用 <router-link> 组件:

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

编程式导航 在组件方法中使用:

// 普通导航
this.$router.push('/about')

// 带参数导航
this.$router.push({ name: 'About', params: { id: 123 } })

// 替换当前路由(不保留历史记录)
this.$router.replace('/about')

// 前进/后退
this.$router.go(1)  // 前进一步
this.$router.go(-1) // 后退一步

路由参数处理

定义带参数的路由

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

获取路由参数 在组件中访问:

this.$route.params.id

导航守卫

全局前置守卫

router.beforeEach((to, from, next) => {
  // 进行权限验证等操作
  next()
})

路由独享守卫

{
  path: '/admin',
  component: Admin,
  beforeEnter: (to, from, next) => {
    // 路由进入前的逻辑
    next()
  }
}

组件内守卫

export default {
  beforeRouteEnter(to, from, next) {
    // 组件渲染前调用
    next()
  },
  beforeRouteUpdate(to, from, next) {
    // 路由改变但组件复用时调用
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 离开路由时调用
    next()
  }
}

路由懒加载

通过动态导入实现路由懒加载:

const User = () => import('../views/User.vue')

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

嵌套路由

实现嵌套路由:

{
  path: '/user/:id',
  component: User,
  children: [
    {
      path: 'profile',
      component: UserProfile
    },
    {
      path: 'posts',
      component: UserPosts
    }
  ]
}

在父路由组件中添加 <router-view> 显示子路由:

<div>
  <h2>User</h2>
  <router-view></router-view>
</div>

以上方法涵盖了 Vue 中路由导航的主要实现方式,可根据项目需求选择适合的方案。

vue实现路由导航

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

相关文章

验证码实现vue

验证码实现vue

验证码实现(Vue) 使用组件库(如Element UI) Element UI提供了现成的验证码组件,可直接集成到Vue项目中。 安装Element UI: npm install elem…

vue实现购物按钮

vue实现购物按钮

Vue 购物按钮实现方法 基础按钮实现 使用 Vue 的模板语法创建基础按钮组件,绑定点击事件处理购物逻辑: <template> <button @click="addToC…

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return { f…

vue实现打字机

vue实现打字机

Vue实现打字机效果 在Vue中实现打字机效果可以通过动态更新文本内容并添加延迟来实现。以下是几种常见的实现方法: 使用setInterval实现 <template> <d…

vue实现人脸识别比对

vue实现人脸识别比对

Vue 实现人脸识别比对的方法 使用现成的人脸识别 API 通过调用第三方人脸识别 API(如 Face++、百度 AI、腾讯云等)实现比对功能。注册开发者账号获取 API Key 和 Secret,…

vue弹幕实现不重叠

vue弹幕实现不重叠

实现 Vue 弹幕不重叠的方法 CSS 定位与动画控制 通过绝对定位和动态计算弹幕轨道高度,确保弹幕在不同轨道上运行。每条弹幕占据固定高度的轨道,避免重叠。 // 弹幕轨道高度计算 const tr…