当前位置:首页 > VUE

vue中实现路由跳转

2026-01-21 01:59:22VUE

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: '/', component: Home },
  { path: '/about', component: () => import('./views/About.vue') }
]

const router = new VueRouter({
  routes
})

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

声明式导航

使用 router-link 组件创建导航链接

<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>

添加 active-class 指定激活样式

<router-link to="/about" active-class="active">关于</router-link>

编程式导航

在组件方法中使用 this.$router.push

methods: {
  goToAbout() {
    this.$router.push('/about')
  }
}

使用命名路由跳转

vue中实现路由跳转

this.$router.push({ name: 'user', params: { userId: '123' } })

带查询参数跳转

this.$router.push({ path: 'register', query: { plan: 'private' } })

路由传参

通过 params 传递参数

// 路由配置
{ path: '/user/:id', component: User }

// 跳转方式
this.$router.push({ path: `/user/${userId}` })

通过 props 解耦

// 路由配置
{ path: '/user/:id', component: User, props: true }

// 组件接收
props: ['id']

导航守卫

全局前置守卫

vue中实现路由跳转

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

组件内守卫

beforeRouteEnter(to, from, next) {
  // 在渲染该组件的对应路由被确认前调用
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

路由懒加载

使用动态导入实现懒加载

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

const router = new VueRouter({
  routes: [{ path: '/users/:id', component: UserDetails }]
})

嵌套路由

配置子路由

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        path: 'profile',
        component: UserProfile
      }
    ]
  }
]

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

<div class="user">
  <h2>User {{ $route.params.id }}</h2>
  <router-view></router-view>
</div>

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

相关文章

vue 路由 实现

vue 路由 实现

Vue 路由实现方法 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现 Vue 路由的详细步骤: 安装 Vue Router 通过 npm 或 ya…

Vue实现路由监

Vue实现路由监

Vue实现路由监听的方法 在Vue中,可以通过多种方式监听路由变化,以下是常见的实现方法: 使用Vue Router的全局前置守卫 router.beforeEach((to, from, n…

js实现页面跳转

js实现页面跳转

使用 window.location.href 通过修改 window.location.href 实现页面跳转,直接赋值目标 URL 即可。 window.location.href = '…

vue 实现登录跳转

vue 实现登录跳转

实现登录跳转的核心逻辑 在Vue中实现登录跳转通常涉及路由守卫、状态管理和API交互。以下是具体实现方式: 配置路由守卫 在路由配置文件中添加beforeEach守卫,检查用户是否已登录。未登录时重…

vue实现路由历史

vue实现路由历史

Vue 实现路由历史管理 在 Vue 中,路由历史管理通常通过 Vue Router 实现。Vue Router 提供了两种历史记录模式:hash 模式和 history 模式。以下是具体实现方法。…

动态路由的实现vue

动态路由的实现vue

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