当前位置:首页 > 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)。它通过动态映射组件到路由实现页面无刷新切换,同时支持嵌套路由、路由参数、导航守卫等高级功能…

php实现跳转

php实现跳转

PHP 实现页面跳转的方法 在 PHP 中实现页面跳转有多种方式,以下是常见的几种方法及其适用场景: 使用 header() 函数 通过 header() 函数发送 HTTP 头部信息实现跳转。注意…

vue路由实现登录

vue路由实现登录

路由守卫实现登录验证 在Vue项目中,可以通过路由守卫(Navigation Guards)来实现登录验证逻辑。路由守卫能在路由跳转前、跳转后或跳转时进行拦截处理。 安装路由依赖 npm inst…

vue路由实现机制

vue路由实现机制

Vue 路由实现机制 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心机制包括路由匹配、导航守卫、动态路由等。 路由匹配 Vue Router 通过路由…

vue实现路由切换

vue实现路由切换

Vue 路由切换实现方法 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router 配置路由 在项目中创建路由配置文…

vue实现内部路由

vue实现内部路由

Vue 内部路由实现方法 Vue 内部路由可以通过 Vue Router 实现,以下是具体实现步骤: 安装 Vue Router 在项目中安装 Vue Router 依赖: npm install…