Determine the number of elements located inside a designated slot

Take a look at this Vue component code:

<template>

    <!-- Carousel -->
    <div class="carousel-container">

        <div ref="carousel" class="carousel>
            <slot></slot>
        </div>

    </div>

</template>

<script>

    export default {

        data() {
            return {
                items: this.$refs.carousel.querySelector('*')
            }
        },

        computed: {
            count: function () {
                return this.items.length;
            }
        },

        created () {
            console.log(this.count);
        }

    }

</script>

The above code is not working, possibly due to trying to reference refs in the data object.

I want to find the number of DOM elements within the .carousel element. What is the best approach to achieve this?

Update

After some research, I discovered an alternative method:

<script>

    export default {

        data() {
            return {
                items: []
            }
        },

        computed: {
            count: function () {
                return this.items.length;
            }
        },

        mounted () {
            this.items = this.$refs.carousel.children;
            console.log(this.count);
        }

    }

</script>

However, I am unsure if this is the most efficient way. While 'best' can be subjective, does anyone know of a more effective approach?

Answer №1

In my opinion, a more concise and direct method for tallying the items within the div tag might look something like this:

<script>

    export default {

        data() {
            return {
                totalItems: 0
            }
        },

        mounted () {
            this.totalItems = this.$refs.gallery.children.length;
            console.log(this.totalItems);
        }

    }

</script>

Answer №2

To access all the items within the .carousel class, you can utilize the following code snippet:

var matched = $(".carousel *");
var totalItems = matched.length;

If you are interested in only the slot count, you can make use of the following code:

var matched = $(".carousel slot");
var totalSlots = matched.length;

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

utilizing various ajax functions

I'm having trouble using additional functions with the "complete:" option in JQuery ajax after the "selectOptionSort" function. Can anyone help me figure out what's wrong? $('#tipos').change(function(){ $("#marcas ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...

What are the steps to install @vue/cli following the deprecation of the Request model in npm?

Currently dealing with Windows 10 and attempting to set up vue/cli by following the provided code from its documentation npm install -g @vue/cli Unfortunately, this code is not working as it produces an error message indicating: npm WARN deprecated [emai ...

Is it possible to utilize the package.json "resolutions" field to replace lodash with lodash-es?

Is it possible to use resolutions in a similar manner as dependencies, but with a different package? I'm specifically curious if this can be done with NPM or Yarn. "resolutions": { "lodash": "npm:lodash-es@^14.7.x" ...

The JavaScript replace function using regex eliminates additional content

There is a content string that includes full YouTube URLs and video IDs. I need to replace the URLs with just the video IDs. The example of the "content" variable: var content = '{GENERICO:type="youtube",id="DluFA_AUjV8"}{GENERICO:type="youtube",id ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

Exploring the Vue 3 Composition API with TypeScript and Working with Object Keys

Exploring the Vue-3 composition API and seeking guidance on utilizing types with TypeScript in Vue. Looking for more detailed information on how to define object properties and specify keys in TypeScript within the composition API, as the current document ...

Disappearing Cloned Form Fields in jQuery

Hey there! I'm trying to duplicate a section of a form using the code below. But for some reason, the copied fields are only visible for a split-second before they disappear. Can anyone spot any errors that might be causing this strange behavior? jQu ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Navigate to a specific element indicated in the location hash once it has been dynamically loaded during the page's loading process

When sending an element ID via the location hash, it looks like this: https://example.com/object/id#sub-object Yet, the set of sub-object elements is loaded dynamically from an API after the page loads. What's the best way to scroll the viewport to ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

verifying the user's screen dimensions

I'm currently exploring ways to customize the appearance of my website based on the viewer's screen resolution. I am interested in potentially optimizing the layout for vertical screens on mobile devices, and horizontal screens for laptops. Addit ...

Ways to identify when a specific react component has been clicked

Currently working on developing a klondike game with 4 empty stacks at the start of the game. The initial page layout resembles the first image provided in the link. I am facing an issue where I cannot determine which component was clicked when clicking on ...

The changes made in Express are not reflecting in the MongoDB database as expected

I'm having trouble with my update function. It's not a database issue because delete works fine. Here is the code for my Update route: Can someone please assist me? I've been using console.log to display values in the console, and they all ...

Deactivate a function within Bootstrap JavaScript

Is there a way to temporarily disable a function within Bootstrap after a click event? <a href="#"><span class="glyphicon glyphicon-triangle-right" id="btn04" onclick="myfun();"></span></a> Additionally, I am looking for a soluti ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...