如何将 class 分配给模板参考? -- VueJS 3 打字稿组件 API
How to assign class to template ref? -- VueJS 3 Typescript Component API
如何使用 Vue 3 Composition API 和 typescript 从模板引用中 add/remove CSS 类?
我 运行 遇到以下 modal.value
的打字稿错误:
const modal = ref(null)
returns 对象可能是 'null'.
const modal = ref<HTMLDivElement | undefined>()
return 对象可能是 '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>
这两个选项都有效,但是,有人可以解释一下这是不是首选方法。
选项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 将覆盖这些更改。
您可以改用 class binding。如果模板引用 (modal
) 仅用于修改元素的 class 列表:
<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
class 的样式仅设置 CSS visibility
,请考虑改用 v-show
directive:
<div v-show="isShown"></div>
...或 v-if
directive:
<div v-if="isShown"></div>
如何使用 Vue 3 Composition API 和 typescript 从模板引用中 add/remove CSS 类?
我 运行 遇到以下 modal.value
的打字稿错误:
const modal = ref(null)
returns 对象可能是 'null'.const modal = ref<HTMLDivElement | undefined>()
return 对象可能是 '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>
这两个选项都有效,但是,有人可以解释一下这是不是首选方法。
选项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 将覆盖这些更改。
您可以改用 class binding。如果模板引用 (modal
) 仅用于修改元素的 class 列表:
<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
class 的样式仅设置 CSS visibility
,请考虑改用 v-show
directive:
<div v-show="isShown"></div>
...或 v-if
directive:
<div v-if="isShown"></div>