[Vuejs]-How to scroll into variable element with Vue 3?

1👍

First, read through the Vue documentation on template refs. There is a toggle in the top-left of the page where you can switch between Options API and Composition API syntax.

Referencing refs with variables depends on your version of Vue and/or syntax.

<div ref="someRefName"></div>

Vue 2 / Options API

The variable should hold a string matching the ref on the element

const refVar = "someRefName"
this.$refs[refVar].scrollIntoView({ behavior: "smooth" });

Vue 3 / Composition API

The variable should be assigned ref() (import required). The name of the const should match the name of the ref on the element

const someElement = ref() // assigned to some element in the template
someElement.value.scrollIntoView({ behavior: "smooth" });

Options API and Composition API should not be mixed, so only stick with one syntax.

In both cases you can have multiple elements with the same ref name, in which case Vue will create an array of all same name refs, so to access a specific one you would also use an index

Below are some simplified examples. Hopefully they will clear up any remaining questions and you can modify to fit your needs.

Options API codesandbox example

Composition API codesandbox example

👤yoduh

Leave a comment