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?