Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js mounted scroll to specific div

Tags:

vuejs2

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);
    }
},
like image 923
Bas Avatar asked Dec 03 '17 07:12

Bas


2 Answers

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();
 })
}
like image 172
Mukundhan Avatar answered Nov 05 '22 23:11

Mukundhan


Perhaps you could use the lifecycle hooks in Vue

so something like a mounted hook:

mounted:{
  this.goto('porto')
}
like image 41
nishkaush Avatar answered Nov 05 '22 22:11

nishkaush