编程式导航
官方文档:
https://v3.router.vuejs.org/zh/guide/essentials/navigation.html
VueRouter
给每个页面组件,提供了两个路由对象
$route
:当前路由对象,描述了本次请求过程$router
:全局路由对象,描述了 整个路由规则
页面组件中可以通过$router
实现在代码中完成页面跳转,称为编程式导航
编辑查看用户资料页面,添加编程式导航的代码:src/pages/UserDetail.vue
<template>
<div class="detail-container">
<h3>查看用户资料页面</h3>
<button @click="goBack">后退</button>
<button @click="goForward">前进</button>
<button @click="pushHome">回到首页push</button>
<button @click="replaceHome">回到首页replace</button>
</div>
</template>
<script>
export default {
created() {
// 查看路由对象
console.log(this.$router, "this.$router全局路由对象")
console.log(this.$route, "this.$route当前路由对象")
},
methods: {
goBack() {
// 编程式导航:后退,访问上一个历史记录
this.$router.back()
},
goForward() {
// 编程式导航:前进,访问下一个历史记录
this.$router.forward()
},
pushHome() {
// 编程式导航:保留访问记录的情况下跳转到指定路由
// this.$router.push('/home')
this.$router.push({name: 'home'})
},
replaceHome() {
// 编程式导航:不保留访问记录的情况下跳转到指定路由
this.$router.replace({name: 'home'})
}
}
}
</script>