What is the process for accessing getBoundingClientRect within the Vue Composition API?

While I understand that in Vue we can access template refs to use getBoundingClientRect() with the options API like this:

const rect = this.$refs.image.$el.getBoundingClientRect();

I am now attempting to achieve the same using template refs within the composition API in Vue as shown below:

const image = ref(null);
const rect = image.value.getBoundingClientRect();

This approach is functional, but it prompts an undesirable error message:

Object is possibly 'null'

I have also tried the following code, yet the error persists.

const rect = image?.value.getBoundingClientRect(); 

Answer №2

To enhance your referenced element, specify a type and utilize the onMounted hook to exhibit the rectangle:

import { onMounted,ref } from 'vue'
...
const image = ref<HTMLImageElement|null>(null);
//
onMounted(()=>{
    const rect =image.value?.getBoundingClientRect()
    console.log('rect --------------- ', rect)
})

This method is applicable for Nuxt 3 as well

VIEW DEMO

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

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Angular 2's ngModel feature allows for easy data binding and manipulation, particularly

I currently have an array of objects structured like this... this.survey = [ {id: 1, answer: ""}, {id: 2, answer: ""}, {id: 3, answer: ""}, {id: 4, answer: ""}, {id: 5, answer: ""}, {id: 6, answer: ""}, {id: 7, a ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

Reorganizing Firebase data in Ionic 2

I am currently working on an exciting project to develop an Ionic notes application, where users can easily rearrange items in the list using the reorderArray() function. However, I encountered an issue with Firebase resulting in an error message related t ...

Is it possible that I am making a mistake when using the multi-mixin helper, which is causing an unexpected compiler error that I cannot

As I work on creating a multi-mixin helper function that takes in a map of constructors and returns an extended map with new interfaces, I come across some challenges. Let's first look at the basic base classes: class Alpha { alpha: string = &ap ...

Trigger the Angular Dragula DropModel Event exclusively from left to right direction

In my application, I have set up two columns using dragula where I can easily drag and drop elements. <div class="taskboard-cards" [dragula]='"task-group"' [(dragulaModel)]="format"> <div class="tas ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

Generate sample data within a fixture

Currently, I am in the process of working on a project that involves creating users and conducting tests on those users. To generate user data such as first name and last name, I am utilizing the faker tool. My goal is to create a user with these generated ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

It's possible that the "device.interfaces" variable has not been defined

I am currently working on creating a USB driver in TypeScript using the libusb library to adjust my keyboard lighting. However, I encountered an issue where I received a 'possibly undefined' error when trying to retrieve the interface number. The ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

Eliminate using a confirmation popup

My attempts to delete an employee with a confirmation dialog are not successful. I have already implemented a splice method in my service code. The delete function was functioning correctly before adding the confirmation feature, but now that I have upgrad ...

What steps should I take to plan a collaborative code-sharing project?

As I develop various applications utilizing a core framework of my own creation, I am looking for a way to easily manage updates across all these applications. I have structured the code by creating a GitHub project where the main branch consists of the co ...

Using TypeScript with Next.js getStaticProps causes errors

Currently, I am grappling with utilizing getStaticProps along with TypeScript. Initially, I attempted to achieve this using a function declaration: import { Movie } from './movies/movie' import { GetStaticProps } from 'next' export asy ...

Exploring the world of typed props in Vue.js 3 using TypeScript

Currently, I am attempting to add type hints to my props within a Vue 3 component using the composition API. This is my approach: <script lang="ts"> import FlashInterface from '@/interfaces/FlashInterface'; import { ref } from &a ...

Flying around in every essential element within a Vue template

Recently, I made the switch to Typescript for Vue and decided to enable the Volar extension. However, after doing so, I noticed that every HTML intrinsic element (such as section and img) is now being flagged as an error: JSX element implicitly has type &a ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...