What is the best way to retrieve the current height in VueJS using the Composition API?

I am utilizing a Ref to preserve the current height of the active element. My goal now is to transfer this height to the subsequent element that gets clicked on.

<script lang="ts" setup>
import { ref, reactive } from "vue";

defineProps<{
  content: Array<{ title: string; content: string }>;
}>();

const contentRefs = ref<HTMLDivElement | null>(null);
const isToggled = reactive<{ value: number | null }>({ value: null });

const handleClick = (index: number) => (isToggled.value = isToggled.value === index ? null : index);
</script>

<template>
  <div v-for="(item, index) in content" class="accordion" :class="{ open: isToggled.value === index }" :key="index">
    <div @click="() => handleClick(index)">{{ item.title }}</div>
    <div ref="contentRefs" :style="{ minHeight: isToggled.value === index ? contentRefs?.scrollHeight : '0' }">{{ item.content }}</div>
  </div>
</template>

My aim is to retrieve the current height of the active element using contentRefs?.scrollHeight. However, I am encountering an issue where my desired height is not being returned.

Answer №1

Using the ref attribute within a v-for loop requires that the corresponding ref hold an Array value, which will be filled with elements after the component is mounted:

Find out more about Refs inside v-for

You may also need to adjust the maxHeight instead of using minHeight...
Check out the slightly modified code example here: Explore Vue SFC Playground.

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

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Challenges arise when integrating Angular with Firebase, particularly in the realms of authentication and user

Currently, I am working on a project using Angular and Firebase. However, in the auth.service.ts file, Visual Studio Code is not recognizing the imports for auth and User. import { auth } from 'firebase/app'; import { User } from 'fireba ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

The BullMQ library is optimizing performance by efficiently managing Redis connections

Currently, I'm in the process of implementing logic to efficiently reuse redis connections with bullMQ by referring to this specific section in the bullMQ documentation. My setup involves utilizing the latest BullMQ npm version (1.80.6). As per the ...

Exploring the concept of asynchronous subscriptions in Angular

My current issue seems to be related to asynchronous programming, specifically with the subscription not running at the desired time. I typically approach this problem from both the user's and developer's perspectives. User's Perspective: ...

Quasar: construct in development mode

In my quasar.conf.js file, I have environmental settings set up like so: env: { API_URL: ctx.dev ? 'https://dev.apis.test.io/v2/' : 'https://apis.test.io/v2/' } When running the app locally, the development api is used. When ...

The saved editable input number is automatically pushed even without needing to click on save or cancel

I am working with a datatable, chart, and a label that shows the latest added value. The table and chart display time-series data for the last 30 minutes, including the timestamp and a random numerical value between 0 and 999. Every 10 seconds, a new data ...

Is there a way to switch the default text mode from plain to code, such as HTML?

Is there a way to switch from plain text mode to code mode, specifically HTML, in Sublime? I often find the need to change the mode from plain text to HTML when working on projects. ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Retrieve data from the component within anonymous middleware in NuxtJS

Is there a way to retrieve the component data (like infos, similarPosts shown in this example) from an anonymous middleware within a Nuxt.js application? ...

What steps should I take to fix the error "property scrollIntoView of null cannot be read"?

I start a new project using Angular .html file: <a (click)="go()">toto</a> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis ex porttitor semper iaculis. Nam dapibus erat interdum, scelerisque magna et, finibus ...

How can I retrieve a Vuex data property from another Vuex data property?

In order to make color variables easily accessible throughout my Vue app, I have stored them in an array named "colors[]" within the Vuex store. This method works well when accessing the colors within component methods or inline styles. Now, I am storing ...

What is preventing me from accessing a JavaScript object property when using a reactive statement in Svelte 3?

Recently, while working on a project with Svelte 3, I encountered this interesting piece of code: REPL: <script lang="ts"> const players = { men: { john: "high", bob: "low", }, }; // const pl ...

A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs. For instance: venues: [ {venue:1, title: Shoreline} {venue:2, ti ...

What is the correct way to send a file path with '/' to a Laravel route?

Is there a way to pass a file path to a route like this? <a href={{route('route.name',['path'=>'uploads/xyx/'.$id.'/'.$attachment_name])}}>download</a> My goal is for it to hit Route::get('downlo ...

The specified type 'ListRenderItem<IPhotos>' cannot be assigned to type 'ListRenderItem<unknown>'

Can someone assist with resolving this error I'm encountering: Type 'ListRenderItem<IPhotos>' is not assignable to type 'ListRenderItem<unknown> Here is the code snippet: import { Dimensions, Image, ListRenderItem, Pressabl ...

Can the Date class be expanded by overloading the constructor method?

In my dataset, there are dates in different formats that Typescript doesn't recognize. To address this issue, I developed a "safeDateParse" function to handle extended conversions and modified the Date.parse() method accordingly. /** Custom overload ...

Angular transforming full names to initials within an avatar

What is the best way to convert names into initials and place them inside circular icons, like shown in the screenshot below? I already have code that converts the initials, but how do we create and add them inside the icons? The maximum number of icons di ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...

How can you adjust the level of granularity for re-rendering components in Vue?

Currently, I am using a component to display a dynamic table with numerous rows. Whenever new rows are added or existing ones are modified, Vue ends up re-rendering the entire table, leading to a significant delay that I hope to avoid. While I have implem ...