滚动行为VueJS无法正常工作无法正常、行为、工作、VueJS

2023-09-03 08:53:28 作者:伪情人

我正在尝试通过VueJS中的scroll Behaviour进行滚动锚定。

一般情况下,我通过以下方式更改当前路由器:

this.$router.push({path : 'componentName', name: 'componentName', hash: "#" + this.jumpToSearchField})
vue.js快速入门

我的VueRouter定义为:

const router = new VueRouter({
  routes: routes,
  base: '/base/',
  mode: 'history',
  scrollBehavior: function(to, from, savedPosition) {
    let position = {}
    if (to.hash) {
      position = {
        selector : to.hash
      };
    } else {
      position = {x : 0 , y : 0}
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(position)
      }, 10)
    })
  }
});

我的路线:

[
  {
    path: '/settings/:settingsId',
    component: Settings,
    children: [
      {
        path: '',
        name: 'general',
        components: {
          default: General,
          summary: Summary
        }
      },
      {
        path: 'tab1',
        name: 'tab1',
        components: {
          default: tab1,
          summary: Summary
        }
      },
      {
        path: 'tab2',
        name: 'tab2',
        components: {
          default: tab2,
          summary: Summary
        }
      },
      {
        path: 'tab3',
        name: 'tab3',
        components: {
          default: tab3,
          summary: Summary
        }
      }
    ]
  },
  {
    path: '/*',
    component: Invalid
  }
];

假设我在tab1组件上,并且我想跳到tab3组件上的锚"测试"

router.push()之后,我看到scrollBehavior被触发,组件从选项卡1切换到选项卡3,URL也更改了(例如,http://localhost:8080/tab1更改为http://localhost:8080/tab3#test),但窗口位置不是放置在锚点所在的位置,而是仅放置在窗口顶部。

当然,我在tab3组件上有id=";test";的文本区域

哪里可能出错?

推荐答案

使用{left: 0, top: 0}而不是{x: 0, y: 0},它将起作用。

我认为这是Vue文档中的一个错误,因为如果您在控制台上登录savedPosition,您将看到{left: 0, top: 0},当您更改{x: 0, y: 0}时,一切都将完美运行。

编辑2022年3月8日:

现在,documentation一切正常。