当前位置:首页 > 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 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

php实现页面跳转

php实现页面跳转

PHP实现页面跳转的方法 在PHP中,可以通过多种方式实现页面跳转,以下是几种常用的方法: header函数跳转 header("Location: target_page.php"); ex…

vue实现点击跳转路由

vue实现点击跳转路由

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

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

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

实现登录页面跳转的方法 在H5中实现登录页面跳转可以通过多种方式完成,以下是一些常见的方法: 使用JavaScript的window.location方法 通过JavaScript的window.l…

h5实现登录页面跳转

h5实现登录页面跳转

实现登录页面跳转的基本方法 使用HTML5和JavaScript实现登录页面跳转,可以通过表单提交或JavaScript事件触发。以下是几种常见方式: 表单提交跳转 在HTML中创建一个表单,通过…

vue 实现跳转

vue 实现跳转

Vue 实现页面跳转的方法 在 Vue 中实现页面跳转可以通过多种方式,以下是常见的几种方法: 使用 router-link 组件 router-link 是 Vue Router 提供的组件,用…