当前位置:首页 > VUE

vue router怎么实现跳转

2026-02-21 17:44:04VUE

vue router 跳转方法

在 Vue Router 中实现页面跳转有多种方式,主要包括编程式导航和声明式导航两种形式。

编程式导航

使用 router.push 方法可以实现编程式导航跳转,该方法会向 history 栈添加一个新的记录。

// 字符串路径
this.$router.push('/home')

// 对象形式
this.$router.push({ path: '/home' })

// 带查询参数
this.$router.push({ path: '/home', query: { id: '123' } })

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

使用 router.replace 方法会替换当前 history 记录而不是添加新记录。

this.$router.replace('/home')

使用 router.go 方法可以在 history 记录中前进或后退。

vue router怎么实现跳转

// 前进 1 步
this.$router.go(1)

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

声明式导航

在模板中使用 <router-link> 组件创建导航链接。

<!-- 基本用法 -->
<router-link to="/home">Home</router-link>

<!-- 对象形式 -->
<router-link :to="{ path: '/home' }">Home</router-link>

<!-- 命名路由 -->
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

<!-- 带查询参数 -->
<router-link :to="{ path: '/home', query: { id: '123' }}">Home</router-link>

路由传参

通过 params 传递参数需要在路由配置中定义参数名。

vue router怎么实现跳转

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

通过 query 传递参数不需要在路由配置中定义。

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

导航守卫

可以使用导航守卫在路由跳转前后执行特定逻辑。

router.beforeEach((to, from, next) => {
  // 跳转前逻辑
  next()
})

router.afterEach((to, from) => {
  // 跳转后逻辑
})

动态路由

可以通过 addRoute 方法动态添加路由。

router.addRoute({ path: '/about', component: About })

以上方法涵盖了 Vue Router 中实现页面跳转的主要方式,可以根据具体需求选择合适的方法。

标签: 跳转vue
分享给朋友:

相关文章

vue评分实现

vue评分实现

Vue 评分组件实现方法 使用第三方库(如 Element UI) 安装 Element UI: npm install element-ui 引入并注册组件: import Vue from '…

vue 实现搜索

vue 实现搜索

实现 Vue 搜索功能 在 Vue 中实现搜索功能通常涉及以下几个关键步骤: 数据绑定与输入监听 使用 v-model 双向绑定搜索输入框的值,监听用户输入: <template>…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…

vue 实现导出pdf

vue 实现导出pdf

使用 html2canvas 和 jsPDF 实现导出 PDF 在 Vue 项目中安装 html2canvas 和 jsPDF 依赖: npm install html2canvas jspdf 创…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

vue实现展开收缩

vue实现展开收缩

Vue实现展开收缩功能 使用Vue实现展开收缩功能可以通过v-show或v-if指令结合点击事件来控制元素的显示与隐藏。以下提供几种常见实现方式: 基础实现(v-show) <template…