Exploring the Component API in VueJS 3 with Typescript: Learn how to assign a class to a template ref

Is there a recommended way to add/remove CSS classes from a template ref using the Vue 3 Composition API and typescript?

When trying to use modal.value, I encountered the following typescript errors:

  1. const modal = ref(null) results in Object is possibly 'null'.
  2. const modal = ref<HTMLDivElement | undefined>()
    gives Object is possibly 'undefined'.
<template>
    <button @click="hideModal">Hide</button>
    <div class="show" ref="modal"></div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
    ...
    setup(){
        const modal = ref(null)
        const hideModal = () => modal.value.classList.remove('show')

        return {modal, hideModal}
    }
})
</script>

Both Option A and Option B work. Can someone clarify if one is preferred over the other?

Option A:

const modal = ref()
const hideModal = () => modal.value.classList.remove('show')

Option B:

const modal = ref({})
const hideModal = () => (modal.value as HTMLDivElement).classList.remove('show')

Answer №1

It's recommended to avoid DOM manipulation in Vue, as the changes may be overwritten if the component needs to be rerendered.

Instead of directly manipulating the DOM, you can utilize a class binding. This approach will also eliminate the need for a template ref like (modal) if its purpose is solely for modifying the element's class list:

<template>
    <button @click="hideModal">Hide</button>
    <div :class="{ show: isShown }"></div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
    setup(){
        const isShown = ref(false)
        const hideModal = () => isShown.value = true

        return { isShown, hideModal }
    }
})
</script>

If the styling for the show class only involves setting CSS property visibility, consider using the v-show directive instead:

<div v-show="isShown"></div>

...or leverage the v-if directive:

<div v-if="isShown"></div>

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

Storing and Retrieving Cookies for User Authentication in a Flutter Application

I am currently working on developing a platform where, upon logging in, a token is created and stored in the cookie. While I have successfully implemented a route that stores the cookie using Node.js (verified in Postman), I encounter issues when attemptin ...

Smooth scrolling in JavaScript can lead to unexpected jumps when using scroll-margin-top

I am currently working on implementing smooth scrolling into my website using JavaScript. However, I have run into a problem with CSS property scroll-margin-top causing a sudden jump at the end. The CSS I am using for scroll margins looks like this: class ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

What sets apart using (@Inject(Http) http: Http) from not using it?

Following a recent query, I now have a new question. What sets apart these two approaches? Here is the original code I used: import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Component({ viewProviders: [HTTP_PROVIDERS], ..// constructor(h ...

Create a Discord.js bot that automatically deletes any URLs that are posted in the server

Seeking advice on how to have my bot delete any URLs posted by members. I am unsure of how to accurately detect when a URL has been shared, especially since they can begin with https, www, or some other format entirely. Any insights would be greatly apprec ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Setting up the Kik Bot configuration can be a bit confusing at first

After installing @kikinteractive/kik and testing the script in /home/usersite/node_modules/, I find myself at a roadblock. How do I properly import @kikinteractive/kik? 2. Create a bot using the username and API key obtained from . 3. Follow the instruct ...

Exploring Shadertoy's Visual Magic with THREE.js

I am currently attempting to implement this shader on a canvas using THREE.js: . The function I am using usually works for simpler shaders, but for this one, I might need to save the floats as uniforms. I am a bit stuck on this issue. Has anyone encounte ...

Different syntax issues in Firefox and Internet Explorer are causing errors

While this code successfully runs on Firefox, it encounters errors when used on IE. document.getElementById('zip_container').style.borderLeft = '1px solid #D9D9D9;'; In this code snippet, zip_container refers to a div element. If any ...

Executing a Particular Function in PHP with Arguments

As a newcomer to PHP and JavaScript, I'm attempting to invoke a specific function in a PHP file from JavaScript. Here is my code: <script> function load($dID) { $.ajax({ url: "myPHP.php", ...

What are the steps to successfully integrate Vuetify 2.3 or any other packages into a Vue 3 Project?

How can I properly register Vuetify in my main.js file without using Vue alias? After importing Vuetify, all of my components are hidden. Dependencies: "vue": "^3.0.0-rc.7", "vue-router": "^4.0.0-0", &quo ...

Thumbnail Carousel Caption in Bootstrap 3

Is it possible to create a Bootstrap 3 carousel where the image changes when the mouse cursor hovers over the thumbnail under the carousel? Currently, I have a setup with the carousel and thumbnails below it. Typically in Bootstrap, the image changes autom ...

Enhance your slideshow with a stylish fade effect

I found this slideshow on codepen and decided to customize it to make it my own. While everything is working well, I wanted to incorporate a fade effect into the transition between slides. I'm unsure whether I should add something to the CSS file or m ...

"Efficiently fetch data with an Express GET request without the

My goal is to send the client the HTML page (create.html) in response to a GET request triggered by a button click using fetch. I am intentionally avoiding the use of a form due to formatting and potential scalability issues. The code acknowledges that the ...

Nextjs style import function properly on the development server, but faces issues when deployed to production environments

import "../styles.css"; import styles from "react-responsive-carousel/lib/styles/carousel.min.css"; import "react-owl-carousel2/lib/styles.css"; import { Provider } from "react-redux"; import store from "../store/store" function App({ Component, pageProps ...

What are the best strategies for effectively overseeing employees within nativescript?

Currently, I am immersed in a project that combines nativescript-vue and typescript, requiring me to interact with workers. Even though I've delved into the NS documentation and implemented the recommended approach for working with workers, I'm f ...

I encountered a 404 error when attempting to execute the "npm publish" command

While attempting to publish a package to the npm registry, an error is encountered after running the command npm publish. npm WARN prepublish-on-install As of npm@5, `prepublish` scripts are deprecated. npm WARN prepublish-on-install Use `prepare` for buil ...

Eliminating the "undefined" error in TypeScript within a React application

Having recently dived into TypeScript configuration, I encountered an issue when coding and tried to resolve it by encapsulating the code block in an if statement checking for usersData to eliminate the "Object is possibly undefined" errors. However, upon ...

What is the best way to access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...