Introducing the latest feature in Vue.js 3.2: script setup with dynamic $

I am attempting to generate a dynamic summary.

<template>
    <ul>
        <li v-for="(category, i) in categories" :key="i" class="cursor-pointer text-capitalize q-mb-sm" @click="scrollTo('category'+i)">{{ category }}</li>
    </ul>
</div>
.....

</template>
<script setup>
import { ref } from 'vue'
let category0 = ref(null)
let category1 = ref(null)
let category2 = ref(null)
let category3 = ref(null)
let category4 = ref(null)
let category5 = ref(null)
let category6 = ref(null)
let category7 = ref(null)
....
function scrollTo(refName) {
  [refName].value.scrollIntoView({ behavior: "smooth" });
}
...
</script>

Before version 3.2 and the script setup, I utilized this function to scroll to the id, however, I am unsure of how to dynamically create a reference value.

function scrollTo(refName) {
  let element = this.$refs[refName];
  refName.value.scrollIntoView({ behavior: "smooth" });
}

Answer №1

Take a look at this

Starting from version 3.2.25 of Vue, the Refs inside v-for feature has been introduced.
It seems to align closely with what you are attempting to accomplish.

Requires Vue v3.2.25 or higher

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

const list = ref([1, 2, 3])

const itemRefs = ref([])

onMounted(() => {
  alert(itemRefs.value.map(i => i.textContent))
})
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

Vue SFC Playground

Answer №2

Just a quick explanation :


function smoothScrollToElement(refName) {
  document.getElementById('category' + refName).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

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

What are the built-in modules in node.js that handle System calls?

Can you list the built-in modules in Node.js that handle system calls, such as child_process? I'm interested in learning about all the methods within these modules. Thank you! ...

What is the method to retrieve the return value from this ajax request?

Here's a code snippet: var information = { ObtainInfo : function() { var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/info/'+storage.get('apikey'); $.ajax({ url: url, su ...

Svelthree - What is the best way to incorporate edges and lines into a scene?

I'm currently experimenting with adding edges to an object in Svelthree. While I understand how to incorporate a geometry into a scene using mesh, I'm unsure of how to include lines at the edges of the geometry. Referencing the official REPL tu ...

What could be the reason for the malfunction of Twitter Bootstrap's typeahead feature in this case?

Struggling to implement typeahead.js into my current project. Despite having bootstrap loaded, the source code does not mention anything about typeahead. As a result, I included the standalone js file with hopes of making it work. Upon implementation, the ...

Select2 script fails to render properly after returning from Action Result

In my MVC4 application, the index page features JQuery UI tabs that I use to display content updated via Ajax action links. One of the tabs includes a Select2 option box which renders correctly initially but defaults to basic functionality after clicking a ...

Vuetify does not support Tailwind CSS styles

Initially, I integrated Tailwind CSS into my project. However, during the development process, I decided to give Vuetify a try. After adding Vuetify along with vuetify-loader, I encountered an issue where Vuetify functionality was working fine but the styl ...

Modify the string by replacing the second comma with a line break

Looking for a solution to insert a line break after the second comma in a string. The code I'm currently using works, but I'm wondering if using a regex would be a more efficient approach. var data = $('#test1').html(); var position ...

Translate unknown provider in Angular using $translateProvider

Here is the situation I am facing: I am working on an Ionic project and I want to implement internationalization using angular-translate. To achieve this, I have added angular-translate.min.js to my project: <script src="lib/ionic/js/ionic.bundle.js"&g ...

jQuery is unable to locate elements

Here is a JavaScript code snippet that I have: (function($, undefined) { $("a").click(function(event) { //or another elemtnt alert('Hello!'); }) })(jQuery); Also, here is the link being referenced in the code: <a href="http: ...

Tips for clearing an observable in Angular version 4

In the code snippet below, an observable has been created: private permissionSubject = new Subject<any>(); permissionObservable$ = this.permissionSubject.asObservable(); constructor( public apiService: ApiService) { } updatePermissionsDat ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

Ensure that divs remain in a static position within the dialog box

Within the jQueryUI dialog, I have gray boxes at the top and bottom of the visible area represented by the .nav elements. I want these gray boxes to stay fixed in their position even when scrolling within the dialog. Despite setting position: absolute, the ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

Utilize AngularJS to integrate a service into the router functionality

What is the best way to inject a service into my router so that its JSON result will be accessible throughout the entire application? Router: export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterP ...

When navigating back in Next.js, the URL changes but the content remains the same

I'm currently troubleshooting an issue where the content is not updating when I navigate back using the browser's back button or by setting a button with router.back. The URL updates correctly, but the content remains the same. When I refresh the ...

A process of associating a single object with an array containing numerous objects

Can someone help me convert the following data structure? { role:'admin', resource:['calendar','appraisal'], action:['create:any','read:any','update:any','delete:any'] } { role:&apos ...

Issues encountered when trying to implement helperText in mui date picker

Can someone assist with this issue? The helper text is not displaying as expected in the following code snippet: <div className={classes.container}> <LocalizationProvider dateAdapter={AdapterDateFns}> <Des ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...

What is the process for creating a parent container in which clicking anywhere inside will cause a child container (built with jQuery UI draggable) to immediately move to that location?

This is a rundown of tasks that I am struggling to code more effectively: When the bar is clicked anywhere, I want the black dot button to instantly move there and automatically update the displayed percentage below it. Additionally, when I drag the butt ...