vue3 怎么让router.back 返回不触发 onActivated 方法
时间: 2024-03-16 16:45:27 浏览: 24
在 Vue3 中,可以通过在 `router-view` 中添加 `exclude` 属性来实现不触发 `onActivated` 方法。
具体的做法是,在需要不触发 `onActivated` 方法的组件中,在 `router-view` 标签中添加 `exclude` 属性,如下所示:
```html
<router-view :exclude="['componentName']"></router-view>
```
其中,`componentName` 是需要排除的组件的名称。
通过这种方式,就可以让 `router.back` 返回不触发 `onActivated` 方法。
相关问题
$router.back()使用方法详解
$router.back() 是 Vue Router 提供的一个方法,用于在浏览器的历史记录中后退一步。该方法不需要任何参数,直接调用即可:
```javascript
// 后退一步
this.$router.back();
```
需要注意的是,如果当前已经是浏览器历史记录中的第一步(即已经无法后退),再调用 $router.back() 方法也不会有任何效果。
此外,$router.back() 方法与浏览器的后退按钮功能相同,会触发路由的全局前置守卫、全局解析守卫、全局后置钩子等路由钩子函数,所以在使用该方法时,需要注意相应的路由钩子函数是否会对页面产生影响。
我在vue中页面a跳转到页面b 我给页面a绑定的v-model输入框 输入了一些值如何不让页面a的数据被重新刷新而是在页面b通过this.$router.back返回页面a时 页面a绑定的v-model是我刚输入的值而不是被清空 不使用storage
在Vue中,如果你希望页面A的数据在页面跳转后保持不变,可以使用 Vue Router 的导航守卫(Navigation Guards)来实现。具体步骤如下:
1. 在页面A的组件中,使用 `beforeRouteLeave` 导航守卫钩子函数。这个函数会在离开当前路由之前触发。
2. 在 `beforeRouteLeave` 函数中,将输入框的值保存到当前路由的元数据(meta)中。
3. 在页面B的组件中,使用 `beforeRouteEnter` 导航守卫钩子函数。这个函数会在进入目标路由之前触发。
4. 在 `beforeRouteEnter` 函数中,将保存的元数据中的值赋给输入框的绑定值。
下面是一个示例代码:
```vue
// 页面A组件
<template>
<div>
<input v-model="inputValue" type="text" />
<router-link to="/pageb">跳转到页面B</router-link>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: ""
};
},
beforeRouteLeave(to, from, next) {
// 保存输入框的值到元数据
this.$router.meta.savedInputValue = this.inputValue;
next();
}
};
</script>
// 页面B组件
<template>
<div>
<button @click="goBack">返回</button>
</div>
</template>
<script>
export default {
methods: {
goBack() {
this.$router.back();
}
},
beforeRouteEnter(to, from, next) {
// 在进入目标路由之前,将保存的元数据中的值赋给输入框的绑定值
if (from.meta.savedInputValue) {
next(vm => {
vm.inputValue = from.meta.savedInputValue;
});
} else {
next();
}
}
};
</script>
```
在这个示例中,我们在页面A的 `beforeRouteLeave` 导航守卫中保存了输入框的值到元数据中,并在页面B的 `beforeRouteEnter` 导航守卫中将保存的值赋给输入框的绑定值。这样,在返回页面A时,输入框的值就会保持不变。
请注意,这种方法只能在 Vue Router 中实现,而不能使用其他方法(如不使用 storage)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)