Categories
Vue Answers

How to Scroll to an Element with Vue.js?

Spread the love

Sometimes, we want to scroll to an element with Vue.js.

In this article, we’ll look at how to scroll to an element with Vue.js.

Scroll to an Element with Vue.js

We can scroll to an element with Vue.js by assigning a ref to the element we want to scroll to.

Then we can scroll to the element by calling the scrollIntoView method on the element assigned to the ref.

For instance, we can write:

<template>
  <div id="app">
    <button @click="scrollToElement">scroll to last</button>
    <p v-for="n of 100" :key="n" :ref="n === 100 ? 'last' : undefined">
      {{ n }}
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    scrollToElement() {
      const [el] = this.$refs.last;
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
};
</script>

We have the scroll to last button that calls scrollToElement .

Then we have some p element with the last ref being assigned to the last p element.

In the scrollToElement method, we get the element assigned to the last ref with this.$refs.last via destructuring.

Then we call el.scrollIntoView with an object that has the behavior property to change the scroll behavior.

Conclusion

We can scroll to an element with Vue.js by assigning a ref to the element we want to scroll to.

Then we can scroll to the element by calling the scrollIntoView method on the element assigned to the ref.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *