4-6.vue-router的this.$router和this.$route

this.$router的含义

官方解释:通过在 Vue 根实例的 router 配置传入 router 实例。
this.$router可以看成是一个全局的路由对象,它能够在任何组件中使用。一般是用来做自定义的代码跳转,与router-link具有相同的功能

this.$router的使用

1.代码展示
<template>
  <div id="nav">
    <button @click='jumpHome'>home</button>
    <button @click='jumpAbout'>about</button>
  </div>
  <router-view />
</template>

<script>
  export default {
    name: 'App',
    methods: {
      jumpHome() {
        // 这个相当于router-link最普通的用法
        this.$router.push('/Home');
      },
      jumpAbout() {
        // 这个相当于router-link加了一个replace属性
        this.$router.replace('/About');
      }
    }
  }
</script>
<style>
</style>
2.过程分解

在这里插入图片描述

this.$router实现带参数的写法

1.代码展示
<template>
  <div id="nav">
    <button @click='jumpHome'>home</button>
    <button @click='jumpAbout'>about</button>
  </div>
  <router-view />
</template>

<script>
  export default {
    name: 'App',
    methods: {
      jumpHome() {
        // 这个相当于router-link最普通的用法
        this.$router.push({path:'/Home', query:{name: '张三'}});
      },
      jumpAbout() {
        // 这个相当于router-link加了一个replace属性
        this.$router.replace({name:'/About', params:{userId: '123'}});
      }
    }
  }
</script>
<style>
</style>
2.过程分解

对比router-link的to属性,对比着使用即可,只是换了一个实现规则,查看router-link的to属性使用连接:https://blog.csdn.net/weixin_45660035/article/details/111457630

this.$route的含义

表示当前激活的路由对象,一般用来接收传递过来的数据。获取当前的路由路径等。

1.代码展示

配置页面:

import { createRouter, createWebHistory } from 'vue-router'

const Home = () => import('../views/Home.vue')
const About = () => import('../views/About.vue')

const routes = [
  {
    path: '/Home',
    component: Home
  },
  {
    path: '/About/:userId',
    name: 'About',
    component: About
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

home组件:

<template>
  <div class="">
   <p>这是home页面,获取query方式传递的name值:{{this.$route.query.name}}</p>
  </div>
</template>

<script>

export default {
  name: 'Home',
}
</script>

about组件:

<template>
  <div class="about">
    <h1>这是about页面,获取params方式传递的userId值:{{this.$route.params.userId}}</h1>
  </div>
</template>
<script>

  export default {
    name: 'About',
  }
  </script>
2.注意重点
  1. 参数的传递有两种方式query和params这两种,params方式只能和name属性匹配,不然会出错,query方式可以和path还有name属性匹配。看上面代码时一定要注意这两者在匹配页面在js上面的区别;
  2. query和params在传递参数后接收方式分别为this.$route.query.name和this.$route.params.userId
  3. 在推荐传递倾向使用query封装成对象去取。
  4. 在写跳转路径时最前面都要加‘/’,不然在有些情况下会出错。
3.其他方法

this.$route.path:字符串,对应当前路由的绝对路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值