如何将类分配给模板引用?——VueJS 3 Typescript组件API



如何使用Vue 3 Composition API和typescript从模板引用中添加/删除CSS类?

我遇到以下modal.value的打字脚本错误:

  1. const modal = ref(null)返回对象可能为"null">
  2. const modal = ref<HTMLDivElement | undefined>()return对象可能为"未定义">
<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>

然而,有人能解释这两个选项是否有效。

选项A:

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

选项B:

const modal = ref({})
const hideModal = () => (modal.value as HTMLDivElement).classList.remove('show')
应避免DOM操作,因为如果需要重新渲染组件,Vue将覆盖这些更改。

您可以改用类绑定。如果模板ref(modal(仅用于修改元素的类列表:

<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>

如果show类的样式仅设置CSSvisibility,请考虑使用v-show指令:

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

v-if指令:

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

最新更新