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

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage &g ...

What is the best way to ensure that Interface (or type) Properties always begin with a particular character?

I attempted to tackle this assignment using template literals, but unfortunately, I wasn't successful. Here is the interface that I am working with: interface SomeInterface { '@prop1': string; '@prop2': string; '@ ...

Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit: @Input public stringArray: string[]; public newArray: string[]; ngAfterViewInit() { this.newArray = this.stringArray.filter(x => x.includes('a')); } I placed ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

What method can be used to fetch generic type parameter in typescript?

I am having trouble finding the type of E within the code provided below. class A<E> { getParameterType() { // I need to determine the type of E } } class B { } ** Example ** new A<number>().getParameterType() // number new A<B&g ...

Issue encountered while attempting to launch Angular2 project

Having trouble running my Angular2 project, every time I try to use the ng serve command I get an error: Here is the link: I've installed angular 2 using angular-cli with the following steps: 1. sudo npm install -g angular-cli 2. sudo ng new mi-apl ...

Updating from webpack v1 to v2 using webpack-cli results in a tsx error during migration

Encountering an error during the build process after migration, I'm unsure if it's related to the recognition of tsx files or something within them that is causing issues: Failed to compile. Error in ./src/index_app.tsx Module parse fail ...

determining the data type based on the function parameter even when a specific type parameter is provided

Consider this example: type UpdateFieldValue<T extends Record<string, unknown>> = (key: keyof T, value: SomeType) => void The goal is to have SomeType represent the value type of the property (key) within object T, with key being provided t ...

Failed Azure Pipeline due to the absence of the vueapp.key file during the npm run build process

I'm encountering issues while trying to build a Vue app in Azure pipelines. I lack experience with NodeJS and Vue, so I'm unsure about what it requires. My application builds and runs smoothly locally. Any guidance would be highly appreciated. I ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

The TS-Mocha and Chai duo have encountered a hitch: a peculiar error message, TS2695, informing them that the left side of the

Software Versions: "ts-mocha": "^8.0.0", "ts-node": "^10.3.0", "chai": "^4.3.4", Sample Code: expect(wrapper.find(MyListItem)).to.have.length(3); Execution Command: ts-mocha tests/**/*.tsx -r u ...

How can a const be globally defined in a Vuex module based on the root state?

Within my vuex modules, I find myself needing to access the same value from the root state in multiple actions. This leads me to duplicate the code like this: export const actions = { action1({ commit, rootState }, payload) { const companyId ...

What could be the reason why the getParentWhileKind method in ts-morph is not returning the anticipated parent of the

Utilizing ts-morph for code analysis, I am attempting to retrieve the parent CallExpression from a specific Identifier location. Despite using .getParentWhileKind(SyntaxKind.CallExpression), the function is returning a null value. Why is this happening? I ...

Utilize puppeteer and web-vitals in NextJS to retrieve the web performance metrics of a website

I'm currently working on a basic tool in NextJS that uses puppeteer to fetch web vitals data from a given URL. However, I'm facing an issue where the results are not being printed out. What could be causing this problem? const browser = await pup ...

Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript: setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) { let octdctruns: OctDctRun[] = [...this.octDctRuns]; const index = octdctruns.findIndex((o) => o.guid ...

Find the appropriate return type for a TypeScript function based on its argument

Is it feasible in TypeScript to infer the return type of a function based on its arguments? This feature would be beneficial when extracting specific properties from, for example, a database query. Here is an illustration () : type QueryReturnType = { a ...