账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    angular 使用路由缓存RouteReuseStrategy怎样缓存页面的scrollTop呢?
    52
    0

    从订单详情页跳回列表页是还能在原来的位置

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 在Angular中,RouteReuseStrategy主要用于缓存路由组件以提高页面切换性能,但它本身并不直接支持存储和恢复滚动位置。然而,我们可以通过自定义RouteReuseStrategy实现并结合其他方式来达到这个目的。

      以下是一个简单的示例:

      1. 首先,创建一个自定义的RouteReuseStrategy:

      ```typescript import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';

      @Injectable() export class CustomRouteReuseStrategy implements RouteReuseStrategy { private handlers: { [key: string]: DetachedRouteHandle } = {};

      shouldDetach(route: ActivatedRouteSnapshot): boolean { // 根据需要决定哪些路由需要被缓存 return true; }

      store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { this.handlers[route.routeConfig.path] = handle;

      // 存储滚动位置
      if (handle && window) {
        const scrollPosition = { top: window.pageYOffset, left: window.pageXOffset };
        handle['scrollPosition'] = scrollPosition; // 自定义属性用于存储滚动位置
      }
      

      }

      retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { if (!route.routeConfig) return null; return this.handlers[route.routeConfig.path]; }

      shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!this.handlers[route.routeConfig.path]; }

      shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean { return future.routeConfig === current.routeConfig; }

      // 在重新激活路由时恢复滚动位置 restoreScrollPositions(route: ActivatedRouteSnapshot): void { const handle = this.retrieve(route); if (handle && 'scrollPosition' in handle) { window.scrollTo(handle.scrollPosition.left, handle.scrollPosition.top); } } } ```

      1. 注入并使用自定义RouteReuseStrategy:

      typescript @NgModule({ imports: [RouterModule.forRoot(routes)], providers: [{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStrategy }], }) export class AppRoutingModule {}

      1. 在路由事件钩子中调用恢复滚动位置的方法:

      ```typescript import { Router, NavigationEnd } from '@angular/router'; import { CustomRouteReuseStrategy } from './custom-route-reuse-strategy';

      constructor(private router: Router, private routeReuseStrategy: CustomRouteReuseStrategy) { router.events.subscribe(event => { if (event instanceof NavigationEnd) { this.routeReuseStrategy.restoreScrollPositions(this.router.routerState.root.snapshot); } }); } ```

      这样,在页面切换时就可以恢复滚动位置了。请注意,这只是一个基本示例,可能需要根据你的具体需求进行调整。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部