简体   繁体   English

如何使用带有挂载钩子的 scrollIntoView()

[英]How can I use scrollIntoView() with mounted hook

I have a Vue component and the template has some div elements, a few images and a User object passed over from Laravel 6.0 Everything seems to work just fine until I try to use scrollIntoView() with the mounted() function.我有一个 Vue 组件,模板有一些 div 元素、一些图像和一个从 Laravel 6.0 传递过来的用户 object 一切似乎都工作得很好,直到我尝试将 scrollIntoView() 与 mount() ZC1C425268E68384FC1 一起使用From what I can tell the page is trying to scrollIntoView() before it is completely loaded.据我所知,页面在完全加载之前正在尝试 scrollIntoView() 。 If I limit the user object to a small size (just 2 users) everything works fine.如果我将用户 object 限制为小尺寸(只有 2 个用户),一切正常。 But if there is more data it does not scroll to view like it should.但是,如果有更多数据,它就不会像应有的那样滚动查看。 It does work if I use a set timeout function but it looks hackey and not professional.如果我使用设置超时 function 它确实有效,但它看起来很老套而且不专业。

I just want to scroll to a div (the header) after view is mounted/loaded.我只想在视图安装/加载后滚动到 div(标题)。 The div is the first div on the page and has no images (if that even matters). div 是页面上的第一个 div,没有图像(如果这很重要)。 Can anyone help me to solve this?谁能帮我解决这个问题? I have seen that the mounted function only applies to the virtual DOM?我看到挂载的 function 只适用于虚拟 DOM? If so what can we use in Vue that is more like JQuery $(document).ready() but for the specific component and applies to the actual DOM?如果是这样,我们可以在 Vue 中使用什么更像 JQuery $(document).ready() 但对于特定组件并适用于实际 DOM?

  mounted() {       
    var elmnt = document.getElementById("move-to-header");
    elmnt.scrollIntoView(true);
    }
  }

I got it working by using the callback function of my axios request.我通过使用我的 axios 请求的回调 function 让它工作。 I did however need to wrap it in a setTimeout function with no specified number of milliseconds but overall it is working without errors.但是,我确实需要将它包装在 setTimeout function 中,没有指定的毫秒数,但总的来说它可以正常工作。

  get_user(the_name) {
      axios
        .post("/get_users", { the_name: the_name})
        .then(response => {
           this.display_user(response.data);
           setTimeout(() => {
             var elmnt = document.getElementById("move-to-header");
             elmnt.scrollIntoView();
   })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM