当前位置:首页 > VUE

vue 实现路由跳转

2026-02-17 03:33:35VUE

vue-router 的基本使用

安装 vue-router 依赖包

npm install vue-router

在 main.js 中引入并配置路由

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('./views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

声明式导航

使用 router-link 组件进行导航

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

带参数的动态路由匹配

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

编程式导航

使用 router.push 方法

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

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

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

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

使用 router.replace 方法

vue 实现路由跳转

this.$router.replace('/login')  // 不会留下历史记录

路由传参

通过 params 传递参数

this.$router.push({ name: 'User', params: { id: 1 } })

// 在目标组件中获取
this.$route.params.id

通过 query 传递参数

this.$router.push({ path: '/user', query: { id: 1 } })

// 在目标组件中获取
this.$route.query.id

路由守卫

全局前置守卫

vue 实现路由跳转

router.beforeEach((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',
  component: User,
  children: [
    {
      path: 'profile',
      component: Profile
    },
    {
      path: 'settings',
      component: Settings
    }
  ]
}

在父路由组件中添加 router-view

<router-view></router-view>

标签: 跳转路由
分享给朋友:

相关文章

vue路由实现介绍

vue路由实现介绍

Vue 路由实现介绍 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。它通过动态映射组件到路由实现页面无刷新切换,同时支持嵌套路由、路由参数、导航守卫等高级功能…

动态路由的实现vue

动态路由的实现vue

动态路由的实现(Vue) 在Vue中实现动态路由通常涉及以下方法: 基于路由参数(params) 在路由配置中使用动态片段(以冒号开头),例如: const routes = [ { path…

vue实现点击跳转路由

vue实现点击跳转路由

vue实现点击跳转路由的方法 在Vue中实现点击跳转路由,可以通过以下几种方式完成,具体取决于项目使用的路由管理工具(如Vue Router)以及需求场景。 使用router-link组件 rou…

h5实现登录页面跳转页面跳转页面

h5实现登录页面跳转页面跳转页面

实现H5登录页面跳转 在H5中实现登录页面跳转可以通过多种方式完成,以下是几种常见方法: 使用window.location.href window.location.href = '目标页面…

vue实现户籍系统路由实现

vue实现户籍系统路由实现

Vue 实现户籍系统路由方案 户籍系统通常涉及多层级页面和权限控制,以下是基于 Vue Router 的实现方案: 路由模块配置 在 src/router/index.js 中定义路由结构:…

vue路由实现iframe

vue路由实现iframe

Vue 路由实现 iframe 的方法 在 Vue 项目中,可以通过路由配置和组件的方式实现 iframe 的嵌入。以下是具体实现步骤: 创建 iframe 组件 新建一个 Vue 组件用于承载 i…