滚动行为 VueJS 无法正常工作

Yur*_*vko 9 javascript vue.js vue-router

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

通常,我使用以下方式更改当前路由器:

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

我的 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)
    })
  }
});
Run Code Online (Sandbox Code Playgroud)

我的路线:

[
  {
    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
  }
];
Run Code Online (Sandbox Code Playgroud)

假设我在tab1组件上,我想跳转到tab3组件上的锚定“测试

router.push() 之后, 我看到 scrollBehavior 被触发,组件从tab1切换到tab3以及 URL 被更改(例如http://localhost:8080/tab1http://localhost:8080/tab3#test)但是windows 位置不放置在锚点的位置,而只是在窗口的顶部。

当然,我在 tab3 组件上有 id="test" 的 textarea

有什么问题?

小智 10

这在 Vue 3 中对我有用:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, SavedPosition) {
    if (to.hash) {
      const el = window.location.href.split("#")[1];
      if (el.length) {
        document.getElementById(el).scrollIntoView({ behavior: "smooth" });
      }
    } else if (SavedPosition) {
      return SavedPosition;
    } else {
      document.getElementById("app").scrollIntoView({ behavior: "smooth" });
    }
  },
});
Run Code Online (Sandbox Code Playgroud)


Far*_*adi 9

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

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

  • 文档中的一切都很好,在 vue-router 3 的文档中指示为“{x:0,y:0}”,而对于 vue-router 4 则指示为“{left: 0, top: 0}” 。你们只是在这里使用不同版本的 vue-router 。 (3认同)
  • 这值得无数的赞成票。太感谢了。两年来他们的文档怎么出错了? (2认同)

Swe*_*lly 8

我无法获得围绕这项工作的任何其他解决方案,这真的令人沮丧。

最终为我工作的是以下内容:

const router = new Router({
    mode: 'history',
    routes: [...],
    scrollBehavior() {
        document.getElementById('app').scrollIntoView();
    }
})
Run Code Online (Sandbox Code Playgroud)

我将我的 VueJs 应用程序安装到 #app,因此我可以确定它是否存在可供选择。

  • 这实际上是有效的,而 vue 官方文档中的代码示例却不起作用,至少对我来说! (4认同)