当前位置:首页 > VUE

vue路由实现切换

2026-01-17 21:58:08VUE

Vue 路由切换的实现方法

Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)中的页面切换。以下是常见的路由切换方式:

声明式导航

使用 <router-link> 组件实现路由切换,通过 to 属性指定目标路由路径:

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

可以通过 tag 属性指定渲染的标签类型:

<router-link to="/profile" tag="button">Profile</router-link>

编程式导航

在 Vue 组件中通过 this.$router 提供的 API 实现路由跳转:

// 跳转到指定路径
this.$router.push('/home')

// 带参数跳转
this.$router.push({ path: '/user', query: { id: '123' } })

// 命名路由跳转
this.$router.push({ name: 'user', params: { userId: '123' } })

// 替换当前路由(不添加历史记录)
this.$router.replace('/login')

// 前进/后退
this.$router.go(1)
this.$router.go(-1)

路由传参

可以通过以下方式传递参数:

  1. 动态路由匹配

    // 路由配置
    {
      path: '/user/:id',
      component: User
    }
    
    // 组件中获取
    this.$route.params.id
  2. 查询参数

    // 跳转时
    this.$router.push({ path: '/search', query: { keyword: 'vue' } })
    
    // 组件中获取
    this.$route.query.keyword
  3. 命名路由传参

    // 路由配置
    {
      name: 'profile',
      path: '/profile/:userId',
      component: Profile
    }
    
    // 跳转时
    this.$router.push({ name: 'profile', params: { userId: 123 } })

导航守卫

可以在路由切换前后执行逻辑:

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 必须调用 next()
  next()
})

// 路由独享守卫
{
  path: '/admin',
  component: Admin,
  beforeEnter: (to, from, next) => {
    // 验证逻辑
    next()
  }
}

// 组件内守卫
export default {
  beforeRouteEnter(to, from, next) {
    // 不能访问组件实例
    next(vm => {
      // 通过 vm 访问组件实例
    })
  },
  beforeRouteUpdate(to, from, next) {
    // 当前路由改变但组件被复用时调用
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开时调用
    next()
  }
}

路由过渡效果

可以通过 <transition> 组件为路由切换添加动画:

<transition name="fade">
  <router-view></router-view>
</transition>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

路由懒加载

通过动态导入实现路由组件懒加载:

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

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

vue路由实现切换

标签: 路由vue
分享给朋友:

相关文章

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue实现菜单调用

vue实现菜单调用

Vue 实现动态菜单的常见方法 基于路由配置生成菜单 Vue Router 的路由配置可以天然转化为菜单结构,适合权限与路由绑定的系统: // router/index.js const rout…

vue实现本地数据存储

vue实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue实现点击跳转路由

vue实现点击跳转路由

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