滚动行为VueJS无法正常工作 [英] Scroll behaviour VueJS not working properly

查看:0
本文介绍了滚动行为VueJS无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

this.$router.push({path : 'componentName', name: 'componentName', hash: "#" + this.jumpToSearchField})

我的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一切正常。

这篇关于滚动行为VueJS无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆