vue.js 中this.$router.push()的使用

本文介绍了在Vue项目中如何使用this.$router.push()进行内部路由跳转,并解释了为何这种方式不适用于外部链接的跳转。对于外部链接,推荐使用window.location.href或者a标签来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在vue项目中,跳转可以用router-link直接跳到某个页面

因为有时候会需要做一些判断等情况,所以要用到 this.$router.push()

因为外链跳转根本就不在router的设计考虑范围之内,这写都是项目的内部路由配置的,一般可以在routes里面找到

如果想要跳到外部链接,就使用window.location.href以及 a标签的跳转就好

 

转载于:https://www.cnblogs.com/antyhouse/p/9282682.html

### Vue2 中 `this.$router.push` 的用法解释 在 Vue2 中,`this.$router.push` 是一种用于程序化导航的方法,允许开发者通过 JavaScript 实现页面之间的跳转。它不仅可以完成简单的路由切换,还可以携带参数以便目标页面使用这些数据。 #### 1. 基本语法 `this.$router.push` 方法可以接受多种类型的参数,包括字符串、对象等。以下是常见的几种形式及其作用: - **字符串路径** ```javascript this.$router.push('/home'); ``` 这种方式直接指定要跳转的目标路径[^1]。 - **对象路径** ```javascript this.$router.push({ path: '/home' }); ``` 使用对象的形式更加灵活,可以通过 `path` 属性指定目标路径[^1]。 - **命名路由** 如果在路由配置中设置了 `name` 属性,则可以通过命名路由的方式进行跳转: ```javascript this.$router.push({ name: 'Home' }); ``` 此处的 `'Home'` 应与路由配置中的 `name` 属性一致[^1]。 #### 2. 参数传递 除了基本的路径跳转外,`this.$router.push` 还支持带参数的跳转。Vue 提供了两种主要的方式来传递参数:`query` 和 `params`。 - **Query 参数** Query 参数会附加到 URL 上作为查询字符串的一部分,适合公开的数据传输场景。 ```javascript this.$router.push({ path: '/target', query: { id: 1, name: 'John' } }); ``` 在目标页面中,可以通过 `this.$route.query` 获取传递过来的参数: ```javascript const id = this.$route.query.id; // 1 const name = this.$route.query.name; // 'John' ``` - **Params 参数** Params 参数不会直接显示在 URL 中,而是通过路由匹配机制隐式传递给目标组件。这种方式通常适用于动态路由场景。 ```javascript this.$router.push({ name: 'target', params: { id: 1, name: 'John' } }); ``` 在目标页面中,可以通过 `this.$route.params` 获取传递过来的参数: ```javascript const id = this.$route.params.id; // 1 const name = this.$route.params.name; // 'John' ``` 需要注意的是,当使用 `params` 方式时,必须配合命名路由(`name`),而不能单独使用 `path`[^2]。 #### 3. 示例代码 以下是一个完整的示例,演示如何在 Vue2 中使用 `this.$router.push` 并传递参数: ##### 路由配置 ```javascript // router/index.js import Vue from 'vue'; import Router from 'vue-router'; import TargetPage from '@/components/TargetPage.vue'; Vue.use(Router); export default new Router({ routes: [ { path: '/target/:id', // 动态路由 name: 'target', component: TargetPage, }, ], }); ``` ##### 发起跳转 ```javascript methods: { navigateToTarget() { // 使用 query 参数 this.$router.push({ path: '/target', query: { id: 1, name: 'John' } }); // 或者使用 params 参数 this.$router.push({ name: 'target', params: { id: 1, name: 'John' } }); }, }, ``` ##### 目标页面接收参数 ```javascript <template> <div> <p>ID: {{ $route.params.id }}</p> <p>Name: {{ $route.query.name }}</p> </div> </template> <script> export default { mounted() { console.log(this.$route.params); // 输出 { id: '1', name: 'John' } console.log(this.$route.query); // 输出 { id: '1', name: 'John' } }, }; </script> ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值