this.$router.back() 可以在vue3使用吗
时间: 2023-12-06 12:45:34 浏览: 36
可以,在 Vue 3 中,使用 `this.$router` 访问路由器对象的方式已经被废弃。相反,你可以使用 `useRouter` 函数从 Vue Router 包导入,并在组件中使用它。然后,你可以使用 `router` 对象上的 `back()` 方法返回前一个路由。
以下是一个示例:
```javascript
import { useRouter } from "vue-router";
export default {
setup() {
const router = useRouter();
const goBack = () => {
router.back();
};
return { goBack };
},
};
```
在这个示例中,我们从 `vue-router` 包导入 `useRouter` 函数,并在 `setup` 函数中调用它。然后,我们可以使用 `router` 对象上的 `back()` 方法返回前一个路由。最后,我们将 `goBack` 方法暴露给组件,以便在模板中使用。
相关问题
this.$router.back()、this.$router.go(-1)的区别使用
`this.$router.back()` 和 `this.$router.go(-1)` 都可以返回上一个页面,但是它们的使用场景稍有不同。
`this.$router.back()` 是 Vue Router 提供的方法,用于返回上一个访问的页面。它会返回到浏览器的历史记录中最近的一个页面。如果当前页面是从其他页面跳转过来的,那么返回的就是上一个页面。如果当前页面是用户手动输入 URL 进入的,那么返回的就是浏览器中的上一个历史记录。
而 `this.$router.go(-1)` 则是通过跳转到指定的页面来实现返回上一个页面的效果。`go()` 方法接收一个整数参数,该参数表示要前进或后退的步数。如果参数为正数,表示前进;如果参数为负数,表示后退。而 `-1` 表示后退一步,即返回上一个页面。
综上所述,如果你想要返回上一个页面,可以使用 `this.$router.back()`,但如果你需要返回上上个页面或者更多步,就应该使用 `this.$router.go(-n)`。
vue this.$router
在Vue中,this.$router是Vue Router的实例对象,可以用来访问和操作路由。它提供了一些方法和属性,例如:
1. this.$router.push(location):跳转到指定的路由。
2. this.$router.replace(location):跳转到指定的路由,但是不会生成新的历史记录。
3. this.$router.go(n):在浏览器历史记录中向前或向后移动n个步骤。
4. this.$router.back():后退一页。
5. this.$router.forward():前进一页。
6. this.$router.currentRoute:当前路由的信息对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)