Get Element Count from within a Slot

Viewed 3621

Consider the following Vue component:

<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 does not work, and I think that is because I am attempting to reference refs in the data object.

I am trying to get the count of DOM elements within the .carousel element. How should I go about achieving this?

Update

After doing some further research, I have found that it is possible to achieve like so:

<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 not confident that this is the best way to achieve this. I appreciate that 'best' is subjective, but is anyone aware of a 'better' way to achieve this?

2 Answers

I think a simpler, more straightforward way of counting the elements in tag would be more like this:

<script>

    export default {

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

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

    }

</script>

We can get all the elements inside the .carousel class using below

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

if you need only slot count, you can use below

var matched = $(".carousel slot");
var total elements = matched.length;
Related