0
votes

ScrollIntoView returns undefined

I am trying to scroll into the element when navigate to that page:

scrollTo(itemId) {
  this.$refs['item' + itemId].scrollIntoView({
    behavior: 'smooth',
    block: 'center',
    inline: 'nearest',
  })
},

The point is that it's getting called inside the mounted hook. ref is defined itemId is also defined which is a query parameter from vue router but it still throws error in a mounted hook (Promise/async): "TypeError: Cannot read property 'scrollIntoView' of undefined"

What is wrong and how can be it fixed?

1
How do you call scrollTo and how do reference the elements? - Boussadjra Brahim
@BoussadjraBrahim I set inside the div: :ref="'item' + item.itemId" It's inside the loop getting generated. And in mounted hook when I call scrollTo I set argument this.$route.query.itemId - user12009061
@BoussadjraBrahim it looks the reason is this: this.$refs['item' + itemId] which returns undefined but when I console.log this.$refs it returns object with item889 which exists. 889 is also passing to the method as itemId so why it throws undefined? - user12009061

1 Answers

1
votes

It seems that dynamic refs are not ready in mounted hook, so try to watch the $route object and scroll to the desired element :

watch:{
$route:{
    handler(to,from){

         if(to.query.itemId){
           this.scrollTo(to.query.itemId)
         },
    deep:true //because $route is an object
   }
}

}

But I think that you should use something like scroll-behavior