@[TOC]
什么是编程式导航?
编程式导航是通过编写JavaScript代码来实现路由切换的一种方式,与声明式导航(使用<router-link>
)相对。编程式导航允许在Vue组件中以编程方式触发路由的跳转。
使用$router
对象
1. push
push
方法用于在路由之间进行导航,并且会向历史记录中添加一条新的记录。这是最常用的编程式导航方式。
// 示例代码
this.$router.push('/new-route');
2. replace
replace
方法也用于导航,但不会向历史记录中添加新记录。它通常用于在不需要保留导航历史的情况下进行跳转。
// 示例代码
this.$router.replace('/new-route');
3. go
go
方法允许你在浏览器的历史记录中前进或后退若干步,负数表示后退,正数表示前进。
// 示例代码:后退一步
this.$router.go(-1);
示例
<template>
<div>
<button @click="navigateToNewRoute">跳转到新页面</button>
</div>
</template>
<script>
export default {
methods: {
navigateToNewRoute() {
// 使用push方法导航到新路由
this.$router.push('/new-route');
}
}
}
</script>