7

I found this script and works fine when you click on the button. What i want to achieve is when the page load it automatic scrolls to that specific div.

How can i achieve that?

<button id="goto" @click="goto('porto')">Go to porto</button>

<div class="page" ref="porto">
    Porto page
</div>

methods: {
    goto(refName) {
        var element = this.$refs[refName];
        console.log(element);
        var top = element.offsetTop;
        window.scrollTo(0, top);
    }
},

3 Answers 3

9

mounted is called after render, however if we try to scroll immediately on mount, scroll might not work.

a simple setTimeout without a timeout does the trick, this might look ugly, but works like a charm.

mounted() {
 setTimeout(() => {
  scrollToDiv();
 })
}
Sign up to request clarification or add additional context in comments.

3 Comments

I was struggling for a day to figure it out, this has completely helped me.
glad it helped :)
this helped me get unstuck too. curious if anyone knows why this works. is there a better lifecycle event to use or is this a quirk of Vue?
2

Perhaps you could use the lifecycle hooks in Vue

so something like a mounted hook:

mounted:{
  this.goto('porto')
}

Comments

0

I such a case I'm always using the nextTick method.

import { nextTick } from 'vue';

In your mounted method you would simply call:

mounted() {
    nextTick(() => this.goto('porto'));
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.