vue3.0: Router跳转到Vue页面onMounted事件不执行
时间: 2024-10-22 10:21:52 浏览: 163
在 Vue 3 中,`router.push` 或 `this.$router.go` 跳转路由时,如果目标组件是异步加载的,`mounted` 生命周期钩子可能会在组件实际渲染完成前触发,导致某些依赖于DOM的操作(如获取元素)还未执行。这是因为 Vue 的懒加载策略,它会延迟一些非必需组件的渲染,直到首次显示。
如果你希望在导航完成后立即执行 `mounted` 钩子内的操作,可以考虑以下解决办法:
1. 使用 `async` 和 `await` 异步处理:
```javascript
this.$router.push({ name: 'targetRoute' }).then(() => {
// 在这里,组件已经挂载并渲染完成,可以执行mounted里的操作
this.onMountedFunction();
});
```
2. 使用导航守卫(`beforeRouteEnter` 或 `asyncData`):
- 在 `beforeRouteEnter` 守卫中,你可以确保组件已经被挂载并且数据已准备就绪:
```javascript
router.beforeEach((to, from, next) => {
next(vm => vm.onMounted());
});
```
- 或者,在 `asyncData` (仅限单文件组件)里,返回一个 Promise 并在 resolve 时执行 `mounted` 功能:
```javascript
export default {
async asyncData(context) {
await this.$nextTick();
return { data };
},
mounted() {
// ...
}
};
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)