How to implement scrollIntoView in Vue 3 with script setup

Having some trouble with scrolling to a specific element when clicked. I keep getting this error message.

Uncaught TypeError: element.scrollIntoView is not a function

Here is my script

<script setup>
import { ref } from 'vue'

function goTo(refName){
    let element = ref(refName);
   element.scrollIntoView({behavior: "smooth"})
}

</script>

This is the click function

<DayWithText v-for="day in daysOfWeek" :name="day.shortHand" :day="day.day" :date="day.date"  @click.prevent="goTo('test')"/>

And here is the element causing issues

<p ref="test">test</p>

Any ideas on what might be going wrong?

Answer №1

ref('test') doesn't just return

<p ref="test">test</p>
, it actually creates a new ref with the initial value of 'test' (a string).

If you want to access that paragraph, you need to declare it as:

const test = ref(null)

inside the <script setup> block (before mount is called).

After the component has been mounted, you can use the following code:

test.value?.scrollIntoView({behavior: "smooth"})

This will work as expected.

Check out the demo below:

const { createApp, ref } = Vue;
createApp({
  setup() {
    const test = ref(null);
    const goToTest = () => {
      test.value?.scrollIntoView({behavior: "smooth", block: "center"})
    }
    return {
      test,
      goToTest
    }
  }
}).mount('#app')
#app p {
  margin: 200vh 0;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4335362603706d71">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="app">
  <button @click="goToTest">Go to test</button>
  <p ref="test">test</p>
</div>


Behind the scenes, on mount, when the <template> parser encounters a ref, it searches the setup scope for the declared variable with that name. If found and if it's a ref, the current DOM element is placed in that ref's value.

Answer №2

For my scenario

const reference = ref(null);

const scrollPage = () => {
    reference.value.$el.scrollIntoView({behavior: "smooth"});
}

html

<div @click="scrollPage()">scroll to</div>
<p id="reference">Scrolled position</p>

was successful for me

Answer №3

This is my solution to the problem.

<script lang="ts" setup>
const scrollPage = ()=> {
    document.getElementById("upButton")?.scrollIntoView({behavior: "smooth"});
}
</script>
<template>
<div>
   <div id="upButton" class="content">
      Some random text...
   </div>
</div>
</template>

Answer №4

When it comes to typescript, the code would look like this:

    const element = ref<null | HTMLDivElement>(null);

    element.value?.scrollIntoView({behavior: "smooth"})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

Tips for splitting JavaScript files into smaller chunks using Vue CLI 3 and the webpack performance object

I recently completed a project using vue cli v3, and after building it, I encountered 2 warnings: Warning: Asset size limit: The following assets exceed the recommended size limit (244 KiB). This could impact web performance. Assets: js/chunk-vendors ...

Can someone show me how to implement arrow functions within React components?

I am facing an issue while working on a node and react project. Whenever I use an arrow function, it shows an error stating that the function is not defined. Despite trying various tutorials and guides, I am unable to resolve this issue. Below is the snipp ...

Guide to importing a JSON file into Vue.js and HTML

I'm a beginner in Vue and not very familiar with HTML I'm attempting to import data from a JSON file into my interface to display it for the user. Below is the structure of the JSON: [ { "Title": "SOFT-STARTER", "Cod&q ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...

Experiencing unexpected behavior with React Redux in combination with Next.js and NodeJS

I'm in the process of developing an application using Next.js along with redux by utilizing this particular example. Below is a snippet from my store.js: // REDUCERS const authReducer = (state = null, action) => { switch (action.type){ ...

Include an item in a Vuetify model's array of objects

Currently, I am attempting to store the value of a dynamically loaded radio button into an array of objects. These radio buttons serve as options for a set of questions within a form, and my desired output is as follows: [{"question1":{ " ...

Unlocking the attributes of Angular form elements: A guide

Imagine we have a form like this <form name="myForm" data-ng-controller="Ctrl"> <input name="input" data-ng-model="userType" data-description="User Type" required> </form> When working in the controller, we can refer to the input el ...

Persistent error function arises from Ajax request in Laravel

Greetings everyone. I'm currently working on my Laravel application and trying to verify the attendance for a specific date, subject, grade in my database table. If the data exists, I have implemented an if statement to display the desired results bas ...

Angular 6 tutorial: Creating a dynamic side navigation bar with swipe and drag functionality using Angular Material/Bootstrap

I am currently working on implementing a vertical swipeable/stretchable side nav-bar with angular-material in angular 6. However, I have encountered an issue with mouse interactions for stretching the nav-bar. Below is the code snippet: Here is the HTML c ...

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

Updating a Div on your webpage using a JQuery UI dialog: A step-by-step guide

I am currently trying to update my webpage from a JQuery UI dialog, but the code I have so far does not seem to be working. Any assistance or guidance would be greatly appreciated. function submit_new_site() { // These are the input text IDs on the ...

How to insert an image into a toolbar within a Vue + Vuetify SFC

I'm currently adapting code from the repository found at the following link for a personal project: https://github.com/aws-samples/aws-ai-qna-bot.git Issue: My goal is to include a logo in the center of the toolbar between the app drawer and logout b ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Angular JS: Grabbing Text from a Specific div and Copying it to Clipboard

I recently developed a Random Password Generator using Angular JS. Here is how the output appears in the application: <div data-ng-model="password" id="password"> <input class="form-control" data-ng-model="password" id="password" placeholder=" ...

Preventing Page Scroll While New Data is Loading

I am currently working on a React class component that uses Post components. Within this component, there is a button that triggers the loading of more data from the database. The issue I am encountering is that when new data is fetched, the page automatic ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...