Exploring alternatives to ref() when not responsive to reassignments in the Composition API

Check out this easy carousel:

<template>
    <div ref="wrapperRef" class="js-carousel container">
        <div class="row">
            <slot></slot>
        </div>

        <div class="row">
            <template v-for="n in noOfSlides" :key="n">
                <span style="margin-right: 25px;" @click="console.log(n)">O</span>
            </template>
        </div>
    </div>

</template>

This code is using the Options API. The number of slides (noOfSlides) updates correctly and triggers a re-render after mounting.

export default {
    name: 'carousel',
    data() {

        return {
            noOfSlides: 0
        }
    },
    mounted(){
        this.noOfSlides = this.$refs.wrapperRef.querySelectorAll('.js-carousel-item').length;
    }
}

However, there seems to be an issue with the Composition API implementation below. The value of noOfSlides does not update, resulting in the for-loop not re-rendering as expected.

export default {
    name: 'carousel',
    setup() {
        const wrapperRef = ref(null);
        let noOfSlides = ref(0);

        onMounted(function () {
            noOfSlides = wrapperRef.value.querySelectorAll('.js-carousel-item').length; // This line should retrieve the correct number of slides (if more than 0)
        })

        return {
            wrapperRef,
            noOfSlides
        }
    }
}

What could be causing the discrepancy here?

Answer №1

If you're looking for an alternative approach in Vue when working with the DOM, consider using the slots feature:

export default {
  name: 'carousel',
  setup(props, { slots }) {
    const wrapperRef = ref(null);
    let noOfSlides = ref(0);

    onMounted(function () {
      console.log('slots ', slots.default());
      noOfSlides.value = slots.default().length;
    });
    function log(n) {
      console.log('n ', n);
    }
    return {
      wrapperRef,
      noOfSlides,
      log,
    };
  },
};

Check out the DEMO here

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

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...

Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen. I looked at the Materi ...

What is the best way to retrieve the value of the first name using Protractor?

Is there a way to store the value of the first name using a protractor script? The first name is set when the user logs in and corresponds to the name of the logged-in user. I am wondering if this can be done utilizing by.addLocator(). Here is the tag tha ...

What specific regular expression pattern does jQuery employ for their email validation process?

Can jQuery validate email addresses? http://docs.jquery.com/Plugins/Validation Does jQuery use a specific regular expression for their email validation? I want to achieve something similar using JavaScript regex. Thank you! An Update: My Question I ...

Having trouble with Three JS shadows not displaying correctly?

I recently built an interactive 3D model on my website using ThreeJS, but I'm facing an issue with getting the shadows to work properly. As a beginner in ThreeJS, I might be missing out on some crucial steps. Below is the JavaScript code I've us ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

The Nestjs cronjob is having trouble accessing the injected service

After setting up a cronjob to call a service from another module, I encountered an issue where the console logged items were displaying correctly when running the method manually from the endpoint. However, once I added back the cronjob decorator, the serv ...

The Vue application using Axios is sending data to an Express backend, but it is receiving

Introducing the main.js file of my Vue application, currently operating on localhost:8080 and attempting to send data to localhost:8081 (express.js) // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Using jQuery Flot to set a target value and visually indicate its position on the graph

I'm currently using the jquery flot plugin to create graphs. My goal is to mark a specific value on the graph by plotting a horizontal line and displaying its exact value. I have already used markings to draw the line, but I am struggling to figure ou ...

Utilizing Mongoose Schema across various endpoints in an Express application

As a newcomer to Node.js, I am using Mongoose and Express for my project. Within the routes/index.js file, I have defined a userDataSchema as follows: var Schema = mongoose.Schema; var userDataSchema = new Schema({ username: String, username_lower: ...

Infinite loop using jQuery function endlessly

I'm trying to create a jQuery Animation that loops indefinitely, but my current code doesn't seem to be working. Here's what I have: $(document).ready(function() { var i = 0; document.write(i); function runAnimatio ...

Filtering array objects based on elements in another array

I am trying to filter out elements from one array based on matching ids in another array. My first array looks like: const toFilter = [1,4,5] And the second array has a structure similar to this: const foo = [{id: 1, time:XXX}, {id:2, time:XXX}, {id: 3, t ...

Disabling CSS transitions and attempting to alter the style of an HTML element using JavaScript may not consistently work as expected

Currently, I am in the process of creating an animated effect for a website that involves moving two elements' positions over time and resetting them to their original position. Only one element is displayed at a time, and the animation should run smo ...

Angular 2 - Graphic Representation Tool for Visualizing Workflows and Processes - Resource Center

Looking for a library that can meet specific requirements related to diagram creation and rendering. We have explored jsplumbtoolkit, mermaid, and gojs, but none of these fully satisfy our needs. For example, we need the ability to dynamically change con ...

Creating interactive JavaScript elements that can be moved around within a container

I recently faced a challenge while attempting to make draggable elements within a div. The issue arose when I realized that I couldn't figure out how to drag each element individually without affecting the others. My current code only allows for handl ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...

Mobile site's call button functionality is malfunctioning

For the telephone number on my mobile site, I employed the <a href="tel:+1800229933">Call us free!</a> code. However, it seems to be malfunctioning on several devices. Any insight on this issue would be greatly appreciated. Thank you. ...

Issue with JS jQuery: The click event on an li element within an expanded ul does not function properly

I have built a basic webpage to explore jQuery. However, there is an issue that arises when I click on the "Button: another one." It seems to interfere with the event of clicking on the li element, causing it to glitch and not respond. Here is the code: JS ...