How do I add/remove CSS classes from a template ref using the Vue 3 Composition API and typescript?
I am running into the following typescript errors for modal.value:
const modal = ref(null)returns Object is possibly 'null'.const modal = ref<HTMLDivElement | undefined>()return 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>
These two options work, however, could someone explain if this is or is not a preferred method.
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')