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

A step-by-step guide on creating a chainable command in Cypress

Imagine having a variable called username. Now, consider a chainable function that needs to verify whether the username is empty or not. Original Method: if(username !== "") { cy.get('#username').type(username) } Expected Outcome: ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Using JavaScript parameters in a HTML document

I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

What is the most effective way to send a list of objects to a Controller

https://i.stack.imgur.com/oyi5v.png This form is for billing purposes. You can add the item name, quantity, and price multiple times to calculate the total amount. Once you click on submit, all the included items along with other parameters like bill nu ...

Tips for personalizing error messages for the "required" field by utilizing a dictionary feature on VeeValidate in Vue.Js

I am trying to update the error message that appears when an input field with the "cpf" rule is left empty (meaning it does not meet the "required" rule). I believe using the "dictionary method" with custom messages is the solution, but I am struggling to ...

Issue with my JavaScript code for customizing checkboxes: the else condition is not being triggered

I'm currently in the process of customizing my own version of "checkboxes" by styling label elements and moving the actual checkbox off-screen. This is the approach I decided to take based on the design and functionality requirements presented to me. ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

Tips for dynamically updating the API path in VUEX state

Currently, I am working on dynamically updating the API path within my Vuex state. When the page loads, I have set a default path of "example.com/api/datasetA.json" in Vuex. However, I would like this path to be updated to "example.com/api/datasetB.json" b ...

Add option button

Is there a way to dynamically add radio buttons using jQuery or JavaScript and save the data into a database? I have successfully appended input types such as text, textarea, checkbox, and select with options. Here is my code: <!DOCTYPE html> < ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward. When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

Tips for simplifying a JavaScript function

Hello everyone, I just joined StackOverflow and I could really use some assistance with a JavaScript and jQuery issue that I'm facing. Can someone suggest a more efficient way to write the code below?: jQuery(document).ready(function () { $("#ar ...