A comprehensive guide to utilizing VueJS for creating dynamic lists

I am trying to associate my timer with a list in my project

<div class="row row-cols-2 justify-content-md-center" v-else-if="timerData.length <= 4" style="height: 100vh; background: none">
  <div v-for="(t, index) in timerData" :key="t.name" class="col">
    <timer 
      :name="t.name"
      :start="t.start"
      :index="index"
      ref="timers"/> // This will replace the existing component
  </div>
</div>

This is how I plan to access it:

this.$refs.timers.forEach(e => {
  e.foo()
})

Answer №1

It appears that you are utilizing template refs in Vue 3, which have some differences compared to Vue 2. In Vue 3, when using the ref within a v-for, you need to handle it customly to gather the template refs in an array.

To begin with, expose an array to the context:

// App.vue
import { ref } from 'vue'

export default {
  setup() {
    const timers = ref([])
    return {
      timers
    }
  }
}

Next, update the template ref binding to be a method that adds the given element into the array:

<timer :ref="el => timers.push(el)">

You can then access the array like this:

// App.vue
export default {
  setup() {
    //...

    return {
      callTimers() {
        timers.value.forEach(t => t.foo())
      }
    }
  }
}

demo

Answer №2

It appears that this.$refs.timers is only recognized as an array when the v-for directive is applied directly to the elements being referenced. For more information, you can refer to: https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

According to the documentation, when ref is combined with v-for, the resulting reference will be in the form of an array containing the child components that correspond to the data source.

<div class="row row-cols-2 justify-content-md-center" v-else-if="timerData.length <= 4" style="height: 100vh; background: none">
  <timer
    v-for="(t, index) in timerData"
    :key="t.name"
    :name="t.name"
    :start="t.start"
    :index="index"
    ref="timers"
    class="col" />
</div>

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

Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now ...

React component not extending to the bottom of the screen

Within my Index.js file, I have created an Index component that includes a navbar and a landing page layout. I aim to have a showcase section taking up 40% of the width, with the remaining 60% dedicated to a react-bootstrap carousel. The Index component sh ...

Ways to prevent a button from being enabled until a 12-letter text is inputted

I need assistance with disabling a button until a minimum of 12 characters are entered into a text input field. The platform I am working on utilizes Bootstrap and allows for custom JavaScript implementation. Below is my code for a form builder that incl ...

Having trouble linking tables to Node.js with TypeScriptyntax?

I am facing an issue with mapping multiple entities using sequelize. I keep encountering the error message " Error: Profesor.hasOne called with something that's not a subclass of Sequelize.Model". How can I resolve this issue? Below is the code for t ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

Iconic Navigation: Bootstrap 3 Navbar featuring Carousel

I'm currently in the process of developing a website using bootstrap3. Despite watching numerous tutorial videos, I am still facing challenges. One of my goals is to have the logo on the navbar aligning with the left side (which I've achieved ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Unable to dynamically apply styles to an element by utilizing a computed property or method

Experimenting with the spread operator in dynamic styles, which may not be useful in this simple example but is crucial in more complex scenarios involving multiple style objects. Despite trying to use a method with a parameter, it seems to be failing. Eve ...

Utilizing jQuery to establish various AJAX requests through functions on page load and button click

Utilizing a basic ajax call both on page load and click events, where I have defined separate functions for each. Despite using different URLs and parameters in the function, the JSON data from the previous call is still being displayed when clicked. Bel ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

"Is it possible to conditionally render a component depending on the state in

One of the challenges I'm facing is customizing a filter icon from MaterialUI. My goal is to change its color to black when a checkmark is checked, and adjust its position accordingly. Additionally, when a box is checked, it should fill in setFilters. ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

Looking for a single solution to have my background image in CSS cover the entire screen on both my computer and cell phone

I used the following code in my demo .html file: body{ background-image: url('https://i0.wp.com/www.socialnews.xyz/wp-content/uploads/2020/10/26/5573c6f0bee7ca021f4a8aecbaf6cbeb.jpg?quality=80&zoom=1&ssl=1'); -webkit-backgroun ...

Is your website designed to adapt effortlessly to all screen sizes?

After uploading my web pages to a server, I've been testing them on various screen sizes and resolutions. Although everything looks good on larger screens, it's not scaling well on smaller resolutions like 800 x 600, 640 x 480, and 240 x 320. Cou ...

How can I create a fixed-top navbar with CSS that sticks when scrolling?

Having two top navbars on a single page can be tricky. One is fixed in its position, while the other is sticky. But when scrolling down, the sticky navbar fails to stay on top of the fixed one: https://i.sstatic.net/4mUAZ.png Furthermore, as you scroll d ...

Update all CDK packages for the project simultaneously

Is there an efficient method to update all AWS CDK packages in a JavaScript/TypeScript project to a specific version simultaneously? I need a solution that can be integrated into CI/CD pipelines and ensures only the AWS CDK packages are updated without af ...

Material UI Appbar is throwing an error with an invalid hook call

For my project, I needed to create a simple app bar, so I decided to use the code provided on the Material UI website. Here is the component's code that I used: import React from 'react'; import { fade, makeStyles } from '@material-ui/c ...

Tips on wrapping div elements while maintaining equal width in different screen sizes using @media queries

Does anyone have a solution for wrapping divs using @media screen while maintaining equal width on all divs? I've tried using float and inline-block, but can't seem to achieve consistent justified widths. While table-cells maintain equal field wi ...

OctoberCMS: Mastering the Art of Creating a Productive Todo List

After following this specific tutorial, I learned how to set up a simple API and integrate it with VueJS. Everything was going smoothly until I encountered an error while trying to add a new Todo: When attempting to create a new Todo at http://localhos ...

How can I turn off credential suggestions in a React JS application?

Is there a way to disable managed credential suggestion on a React JS web page using a browser? I have tried using the autoComplete=off attribute and setting editable mode with an onFocus event, but the password suggestions are still appearing. Any help wo ...