Emberjs 5.4中路由加载时滚动到窗口顶部

rxztt3cl  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(196)

在Ember 5.4中,当一个新的路线被加载,并且最后一个视图被滚动时,滚动位置保持不变。如果url/路线发生变化,我希望它立即滚动到窗口的顶部。
我使用app/routes/application.js中的以下代码实现了它:

  1. import Route from '@ember/routing/route';
  2. import { action } from '@ember/object';
  3. export default class ApplicationRoute extends Route {
  4. @action
  5. didTransition() {
  6. setTimeout (() => window.scrollTo ({top: 0, left: 0, behavior: 'instant'}), 1);
  7. }
  8. }

字符串
但是使用1毫秒的setTimeout对我来说似乎是不好的风格,而且可能容易出错。然而,仅仅使用没有超时的window.scrollTo ({top: 0, left: 0, behavior: 'instant'})是不起作用的,它不能将窗口滚动到顶部。
所以我想我可能使用了错误的事件(/action),但我在文档中找不到更好的事件(eidogg. here:https://api.emberjs.com/ember/5.4/classes/Route)。
这个问题已经在其他一些堆栈溢出问题中解决了(例如此处:Emberjs scroll to top when changing view),但对于旧版本的ember或其他定义路由的风格,老实说,我不确定具体适用的是什么,因为我是ember的新手,无法在版本和弃用文档以及不同版本中的不同风格的丛林中找到我的方法来获得答案这个问题

q35jwt9p

q35jwt9p1#

实现这一点的最快(也有点天真)方法是从RouterService(通过@service router访问)使用routeDidChange
在应用的 Boot 早期,您可以配置滚动行为:

  1. // in an existing file, app/router.js
  2. // this doesn't use the ember router, so idk if I'd recommend this
  3. import EmberRouter from '@ember/routing/router';
  4. class Router extends EmberRouter {
  5. // ...
  6. constructor() {
  7. super(...arguments);
  8. this.on('routeDidChange', () => window.scrollTo(0, 0));
  9. }
  10. }

字符串

  1. # generate the normally implicit, yet still top-level route
  2. ember g route application
  1. import Route from '@ember/routing/route';
  2. import { service } '@ember/service';
  3. export default class ApplicationRoute extends Route {
  4. @service router;
  5. // initial app set up can go in here
  6. beforeModel() {
  7. this.router.on('routeDidChange', () => window.scrollTo(0, 0));
  8. }
  9. }

的数据
需要记住的是,导航和滚动通常是有状态的,所以使用上面的代码,当单击后退按钮时,您仍然会滚动到页面顶部。有些人喜欢这样,有些人不喜欢。浏览器默认设置是维护滚动位置,这需要维护有关滚动位置的历史状态-这有点棘手,因为人们倾向于调整窗口大小,这会改变滚动坐标,打破任何你能跟踪的状态。

展开查看全部

相关问题