Vue3's onMounted hook fails to function properly when page is reloaded

I've implemented a function that checks for truncated text and, if found, displays a button to expand the hidden content.

I have created a code demo with detailed explanations. Although I am not encountering any errors, the logic does not seem to be working as expected. Any guidance or feedback would be highly appreciated.

SCRIPT:

const info = ref<HTMLElement | null>(null)

onMounted(() => {
  // initialize 'info' reference status
  checkInfoRefStatus()
})

function checkInfoRefStatus() {
  if (info.value) {
    const selectedElement = info.value
    return isTextTruncated.value = selectedElement.scrollHeight > selectedElement.clientHeight
  }
}

TEMPLATE:

<div>
  <div ref="info" :class="isExpanded ? 'truncate' : ''">
    {{ data?.information }}
  </div>
  <span
    v-if="isTextTruncated"
    @click="isExpanded = !isExpanded"
  >
    {{ toggleCtaLabel }}
  </span>
</div>

CODE DEMO

Answer №1

The query is missing a crucial element:

<script>
...
const information = ref<HTMLElement | null>(null)

Using the script tag causes

ref < HTMLElement | null > null
to be interpreted as a JavaScript expression, which surprisingly does not throw syntax errors but also doesn't define information as a Vue reference.

It is recommended to correct it to:

<script lang="ts">
...

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 the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

Tips for blocking the insertion of "Emoji & Symbols" into an input field

Currently, I am utilizing Vue JS, but I am willing to consider vanilla JS suggestions as well since they both serve the same purpose. My objective is to block default emojis from being inserted into a text field through either the IOS keyboard or the (CMD ...

Tips for bypassing switch statements in typescript while handling discriminators?

Is there a way to refactor the code below to eliminate the switch case while maintaining type safety? I've encountered this issue several times and am looking for a pattern that utilizes a map or another approach instead of a switch case. function tra ...

Tips for avoiding the use of import statements in Typescript

log.ts contains the code below import {LOG} from './log' LOG.e("tag","error"); LOG.f("tag","error"); LOG.d("tag","error"); I am looking for IntelliSense support in my TS file without affecting the output javascript. I only want this in my Java ...

A guide to simulating ngControl in a Custom Form Control for effective unit testing in Angular

I need some guidance on creating unit tests for a Custom Form Control in Angular 9. The issue arises with this line of code: constructor(@Self() private ngControl: NgControl), which triggers an error: Error: NodeInjector: NOT_FOUND [NgControl]. It seems th ...

Difficulty in loading the uploaded API data into the template

I am facing an issue with a service that retrieves user data based on the Token stored in localStorage. The data is returned correctly until it reaches my component. The problem lies in the code snippet present in my component.ts file: https://i.sstatic.n ...

I'm facing an issue with my Angular project's typescript configuration that is preventing the expect matchers from functioning properly

There seems to be a problem with the TypeScript configuration in my Angular project causing issues with expect matchers. Interestingly, when I remove the Cypress folder from the project, the expect matchers work perfectly fine along with IntelliSense. It a ...

Create a dynamic Prisma data call by using the syntax: this.prisma['dataType'].count()

I'm currently working on implementing a counting function that can be utilized in all of my objects. In my 'core' file, Prisma is involved in this process. This allows me to execute commands like this.user.count() or this.company.count() I ...

What could be the reason behind my Vue file triggering a TS6504 error and suggesting to "allowJs"?

My Vue 3 project, which incorporates TypeScript, is encountering an issue when I attempt to execute vue-tsc --noEmit. error TS6504: File '/proj/src/pages/Index.vue.__VLS_template.jsx' is a JavaScript file. Did you mean to enable the 'allowJs ...

Trouble with Laravel Echo not receiving Pusher notifications

I watched some tutorials about echo and pusher. I followed all the necessary steps to configure my project, but I am not seeing object notifications on the browser. I uncommented the line App\Providers\BroadcastServiceProvider::class, In Vue ...

Property initialization status not being inherited by class

I'm encountering a situation where the properties of the base class are not being recognized as initialized in the extended class when I inherit a class. I'm unsure if this is a TypeScript or TSLint issue, as my Google search didn't yield re ...

The class "Generic" inherits from the "Events.EventEmitter

My WebStorm keeps showing the error message below repeatedly, despite my script compiling and running without any issues. Any ideas on why this is happening? Error:(6, 9) TS2322:Type 'AnotherRandomClass' is not assignable to type 'A'. ...

Display fades to black in React project utilizing Typescript

Hi there! I've been working on a React TypeScript app, and I encountered an issue where my screen suddenly goes blank. After a hard refresh, it goes back to normal, but I'm still puzzled because the console doesn't show any errors. I suspect ...

The parameter 'prevState: Stock[]' does not match the expected type 'SetStateAction<Stock[] | []>'

I'm currently diving into TypeScript and I encountered the following error message that has me stumped. Interestingly, the code runs smoothly without TypeScript. Can anyone provide guidance on how to resolve this issue? Error details: Argument of typ ...

Exploring the Potential of Nested useFetch Functionality within Nuxt 3

Is there a way to achieve nested fetching in Nuxt 3? I have two APIs and the second API needs to be triggered based on a value returned from the first API. I attempted the code snippet provided below, but it is not working because page.Id is null when it ...

Is it acceptable to utilize useCallback within a nested function structure?

I'm looking at some (TypeScript) code that looks like this: export const UniqueComponent = React.memo((props: DemoComponentProps) => { const [value1, setValue1] = React.useState<string | undefined>(''); const [value2, setVal ...

Mastering the Conversion from NGRX Effect to NGRX Effect v15

I am currently working on converting the code snippet to NGRX 15. As a newcomer to Angular, I could use some guidance. "@ngrx/effects": "^15.4.0" @Injectable() export class SnackbarEffects { @Effect({ dispatch: false }) cl ...

Obtain one option from the two types included in a TypeScript union type

I am working with a union type that consists of two interfaces, IUserInfosLogin and IUserInfosRegister. The TUserInfos type is defined as the union of these two interfaces. export interface IUserInfosLogin { usernameOrEmail: string; password: string; } ...

Retrieving data asynchronously from an ant-design vue form by utilizing the onValuesChange method

One of the current challenges I'm facing is integrating a form submission feature with data being sent to the backend using ant-design-vue. My goal is to provide users with instant feedback as they enter information into the fields, where their input ...

The ngModel value in Angular is displayed, but it appears to be blank

ngModel is displaying the value, however it is still considered empty by required validation. Adding an empty space after the value resolves this issue. Snippet to retrieve the name <div (click)="getName(item.name)"></div> <input matInput ...