当前位置:首页 > VUE

vue实现页面跳转路由

2026-02-24 10:16:17VUE

vue-router 基础使用

安装 vue-router 依赖包

npm install vue-router

在 main.js 或 router/index.js 中配置路由

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

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

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 样式类

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

编程式导航

在方法中使用 $router API

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

使用命名路由

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

路由传参

通过 params 传递参数

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

// 导航方式
this.$router.push('/user/123')

通过 query 传递参数

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

在组件中获取参数

this.$route.params.userId
this.$route.query.id

路由守卫

全局前置守卫

router.beforeEach((to, from, next) => {
  // 登录验证逻辑
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

组件内守卫

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

动态路由

添加动态路由

router.addRoute({
  path: '/new-route',
  component: NewComponent
})

删除路由

router.removeRoute('route-name')

路由懒加载

使用 import() 实现懒加载

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

const router = new VueRouter({
  routes: [{ path: '/user', component: User }]
})

嵌套路由

配置嵌套路由

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

在父组件中添加 <router-view>

vue实现页面跳转路由

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

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

相关文章

vue 实现登录跳转

vue 实现登录跳转

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

vue路由可以实现什么

vue路由可以实现什么

Vue 路由的核心功能 Vue Router 是 Vue.js 官方的路由管理器,主要用于构建单页面应用(SPA)。它通过管理 URL 与组件的映射关系,实现页面间的无刷新跳转。 路由的基本实现 动…

Vue实现路由监

Vue实现路由监

Vue 实现路由监听的方法 在 Vue 中可以通过多种方式实现路由监听,以下是常见的几种方法: 使用 watch 监听 $route 对象 通过 Vue 的 watch 功能可以监听 $route…

vue 实现登录跳转

vue 实现登录跳转

实现登录跳转的基本流程 在Vue中实现登录跳转通常涉及以下几个核心步骤:路由配置、登录表单处理、状态管理及导航守卫。以下是具体实现方法: 路由配置 在router/index.js中配置登录页和需要…

vue 实现页面跳转

vue 实现页面跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转可以通过多种方式,主要包括使用 Vue Router 提供的导航方法和原生 JavaScript 的方式。 使用 Vue Router 的 ro…

实现js页面跳转页面

实现js页面跳转页面

使用 window.location.href 通过修改 window.location.href 实现跳转,浏览器会加载新页面并记录到历史记录中: window.location.href = "…