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