vue 中this.$router 和 this.$route

x33g5p2x  于2021-11-12 转载在 Vue.js  
字(1.4k)|赞(0)|评价(0)|浏览(331)

通过注入路由,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前的路由。

注入路由,在 mian.js 中引入 路由,并且注入。

  1. import router from './router';
  2. new Vue({
  3. el: '#app',
  4. router,
  5. ...
  6. mounted() { }
  7. })

可以理解为:

  • this.$router 相当于一个全局的路由对象,包含路由相关的属性、对象 (如 history 对象) 和方法,在任何页面都可以通过 this.$router 调用其方法如 push() 、go() 、resolve() 等。
  • this.$route 表示当前的路由对象。每一个路由都有一个 route 对象,它是一个局部的对象,可以获取当前路由对应的 name , paramspath , query 等属性。
    this.$router 等同于 router。在 main.js 中,我们直接引入了 router 则可以使用类似这样的方式 router.push() 调用相关属性或者方法。

使用: 以 push() 方法为例

在 vue 项目开发中, 我们通常使用 router.push() 实现页面间的跳转,称为编程式导航。这个方法会向 history 栈中添加一个历史记录,但用户点击浏览器的后退按钮时,就会回到之前的 URL。
当我们点击 时,会在内部调用 router.push() 方法。

push方法调用:

  1. //字符串
  2. this.$router.push('home') //->/home
  3. //对象
  4. this.$router.push({path:'home'}) //->/home
  5. //命名的路由
  6. this.$router.push({name:'user', params:{userId: '123'}}) //->/user/123
  7. //带查询参数,变成 /register?plan=private
  8. this.$router.push({path:'register', query:{plan:private}})
  9. const userId = '123';
  10. //这里的 params 不生效
  11. this.$router.push({path:'/user', params:{userId}}); //->/user

params 传参,push 里面只能是 name: 'xxx', 不能是 path: 'xxx',因为 params 只能用 name 来引入路由,如果这里写成了 path ,接收参数页面会是 undefined。

路由传参的方式:

  1. 1、手写完整的 path:
  2. this.$router.push({path: `/user/${userId}`});
  3. 获取参数:this.$route.params.userId
  4. 2、用 params 传递:
  5. this.$router.push({name:'user', params:{userId: '123'}});
  6. 获取参数:this.$route.params.userId
  7. url 形式:url 不带参数,http:localhost:8080/#/user
  8. 3、用 query 传递:
  9. this.$router.push({path:'/user', query:{userId: '123'}});
  10. 获取参数:this.$route.query.userId
  11. url 形式:url 带参数,http:localhost:8080/#/user?userId=123

相关文章

最新文章

更多