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:
const modal = ref(null)
results in Object is possibly 'null'.
gives Object is possibly 'undefined'.const modal = ref<HTMLDivElement | 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')