在 Vue 中,登录成功后跳转首页除了使用 this.$router.push() 之外,还有其他几种方式

1. 使用 this.$router.replace():

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

replace 和 push 的区别是,push 会向 history 添加一个新记录,而 replace 不会向 history 添加新记录,而是替换掉当前的 history 记录。

2. 使用 router.push():

this.$route.router.push('/home')

因为 this.$router 与 router 实例是同一个,所以这两种方式实现同样的功能。

3. 编程式导航 - router.push():

router.push('/home')

在组件外部直接操作 router 实例,产生路由跳转。

4.命名路由导航:

router.push({ name: 'home' })

如果要跳转的路由有命名,可以直接使用命名进行导航。

5.使用 router-link 组件:

<router-link to="/home"></router-link> 

在模板中使用 router-link 组件产生导航。

除此之外,我们还可以通过 JS 直接修改浏览器 URL 来实现导航的效果。所以,登录成功后跳转首页的方式可以有:- this.$router.push()
- this.$router.replace()
- router.push()
- 命名路由
- <router-link> 组件
- JS 修改浏览器 URL这几种方式的选择取决于是否需要向 history 中添加记录、是否已经定义了命名路由等因素。但无论选择何种方式,最终的效果是一致的 - 跳转到首页!我个人更倾向于使用 this.$router.push() 或 router.push(),因为这两种方式简单易读,并且可传参。但如果你有特殊的需求,其他方式也同样值得掌握。

猜你喜欢

转载自blog.csdn.net/qwe0415/article/details/130349898