简体   繁体   中英

Vue 3 - Always scroll to specific position on page when component appears

I have a basic form component and that shows up once I click a button (router is not used). I want the scroll position of the form to scroll down a bit (ex. y-axis of 40) once the form shows up, but I'm not entirely sure how to achieve this. There are various examples about this, but I couldn't get any of them to work. Can someone kindly advice a solution for this, please? I also started using vue 3.

<template>
    <div class="appointment-wrapper" :class="[showForm ? 'appointment' : 'appointment-success']">
        // Scroll down to a certain point
        // ....
            <form @submit.prevent="validateForm" novalidate>
            // ....
            </form>
        </div>
    </div>
</template>

you can use window.scrollTo(0, 40) if the condition is true after you clicked the button.

 Vue.createApp({ data() { return { showForm: true } }, mounted() { if (this.showForm) window.scrollTo(0, 400) // only demo value - use 40 } }).mount('#options-api')
 #options-api { height: 1000px; }
 <script src="https://unpkg.com/vue@next"></script> <div id="options-api"> <h1>hidden title</h1> </div>

If you need to scroll to an element position

document.getElementById(el).scrollIntoView();

Or if you need to scroll by the axis

window.scrollTo(0, 1000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM