Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code.

MainContainer.vue

<template>
  <div class="main-container" ref="mainContainer">
    <button @click="randomBackgroundColor">Random Background Color</button>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, Ref} from 'vue';
export default defineComponent({
  setup() {
    const mainContainer = ref(null)

    const randomBackgroundColor = () => {
      mainContainer.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]
    }
    return { mainContainer, randomBackgroundColor }
  }
});
</script>

<style scoped>

</style>

The above snippet yields an error message:

ERROR in /webapp_vue/src/components/pc/MainContainer.vue.ts
8:20-25
[tsl] ERROR in /webapp_vue/src/components/pc/MainContainer.vue.ts(8,21)
      TS2339: Property 'style' does not exist on type 'Ref<null>'.

webpack 5.28.0 compiled with 1 error in 15963 ms

I attempted a couple of solutions, but unfortunately, they did not resolve the issue.

const mainContainer = ref(null) as Ref<HTMLElement | null>
// or
const mainContainer = ref<HTMLElement | null>(null)

If anyone can guide me on the appropriate way to handle DOM elements within the Vue 3 template using Typescript, I would greatly appreciate it.

Thank you.

Answer №1

As the reference mainContainer is being used, it is essential to first access its value:

function generateRandomColor() {
    mainContainer.value.style.backgroundColor = ["purple", "orange", "pink", "cyan", "magenta"][Math.floor(5 * Math.random())];
}

Answer №2

Enter your reference like this :

const container = ref<HTMLDivElement | null>(null)

then utilize .value to reach the element :

container.value.style.backgroundColor = ["orange", "purple", "pink", "teal", "brown"][Math.floor(5 * Math.random())]

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

Component library for Vue-cli 3 with built-in support for server-side rendering

I am in the process of developing a custom component library that I intend to distribute across various domains. Domains: Each domain is equipped with its own instance of Nuxt Every domain has included my-component-lib in their package.json Additional ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

What's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

What is the best way to retrieve all SVG objects within a specific area in an Angular application?

I am currently developing an SVG drawing application and have implemented a tool that enables users to select all shapes within a rectangular area. However, I am facing the challenge of detecting the SVG shapes located underneath the selected rectangle. ...

What are the steps to resolve the "EADDRINUSE: address already in use :::3000" error in an integration test?

While testing my simple endpoint using jest and superTest in my TypeScript project, I encountered the listen EADDRINUSE: address already in use :::3000 error. The file app.ts is responsible for handling express functionalities and it is the one being impo ...

What is the best way to retrieve a function's response depending on the parameters provided?

I am trying to figure out how to determine the data types of copied array elements in my code. let inputArray = [ { test: 1, }, { test: 2, }, ]; function clone(array: any[]): any[] { return Array.from(inputArray); } ...

I'm perplexed as to why I'm receiving null for my context. Could it be due to a TypeError

Recently diving into Next Js and TypeScript, I encountered the following error: Unhandled Runtime Error TypeError: this.context is null Here's a snippet from my Layout.tsx file: import { FC } from 'react' import { Head } from 'next/d ...

Tips for deleting multiple uploaded images from an array using Vue.Js and updating the UI accordingly

I am currently utilizing VueJs to upload multiple images. I am saving their respective base64 values in an Array to store them in the database. I have also added a remove feature, so when the user clicks on the remove button, it finds the index of that ele ...

Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, w ...

Displaying properties of a class in Typescript using a default getter: Simplified guide

Here is an interface and a class that I am working with: export interface ISample { propA: string; propB: string; } export class Sample { private props = {} as ISample; public get propA(): string { return this.props.propA; } public se ...

What is the best way to create 7 or 8 column grids with Vuetify's v-row and v-col components?

I understand that vuetify's grid system is based on a 12-column flex-box layout, but I would like to customize it to have 7 or 8 columns by default instead of the usual 12. In the code snippet below, you can see my attempt: <v-row> <v-col ...

Issue with scroll position being fixed when using the Quasar loading component in VueJs Quasar after navigating to a new

Encountering an issue with Quasar and VueJs. When utilizing Quasar's Loading.show() method, the scroll becomes stuck upon navigating to a new page, preventing the top of the new page from being displayed. In the router/index.js file, I have configure ...

Nestjs: Can't find property in Mongoose document

I am currently encountering some issues with the following code while using Nestjs along with Mongoose: import { Injectable } from '@nestjs/common'; import { Key, KeyDocument } from '@app/mongo'; import { Model } from 'mongoose&apo ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

The concept of sharing states between components in Vuejs

Seeking advice on the optimal approach for implementing shared states between components in Vuejs. Consider scenario A: a web app displaying a modal with a boolean state show. This state should change when the modal's OK button is clicked, as well as ...

Update the field 'payments._id' in MongoDB to a timestamp

I need to change the value of 'payments._id' to a timestamp. In MongoDB, the 'payments._id' object is automatically generated when inserting a document into the collection. onMounted(async () => { const res = await axios.get(" ...

Using the useContext hook in a TypeScript class component: a step-by-step guide

I am working with a TypeScript class component and have successfully created a context that can be accessed globally. I am interested in learning how to implement this context in a .ts class component and if it is possible to use it in a pure TypeScript ...