Cannot scrollIntoView in vue onMounted hook

245 Views Asked by At

I have a msgHTMLElement that is reactive based on an array ref. The scrollIntoView works as expected when watching the ref.value. As the array is updated, the HTML element representing the data updates and scrolls to the bottom as expected . .

const msgHTMLElement = ref<HTMLElement | null>(null);
watch(messages.value, () => {
    nextTick(() => {
        msgHTMLElement.value?.scrollIntoView({ behavior: "smooth", block: "end"})
    })
    console.log('messages upddated')
})

However, I can't get the list to scroll to the bottom when the element is mounted.

So this works fine as a test

onMounted(() => {  
  if(msgHTMLElement.value)  {
    msgHTMLElement.value.innerHTML = 'blah';
  }
}

But then this doesn't (list is mounted scrolled to the top)

onMounted(() => {        
    msgHTMLElement.value?.scrollIntoView({ behavior: "smooth", block: "end"});      
}

How can I scroll the list to the bottom when the component is mounted?

0

There are 0 best solutions below