Vue 3配合TypeScript时如何无需as any获取input的checked选中状态
Vue 3 + TypeScript 复选框选中值获取方案(无需any断言)
完全可以实现该需求,不需要使用不安全的any类型断言,以下是3种符合TypeScript类型规范的实现方式:
方案1:最小改动,替换any为正确的DOM类型
仅需要将原代码中的any替换为TS内置的HTMLInputElement类型即可,这是DOM接口规范中定义的input元素类型,本身就包含checked属性的类型声明,类型完全安全:
<script setup lang="ts"> function doThing(checked: boolean) { console.log("Do thing", checked); } </script> <template> <input type="checkbox" @change="(event) => doThing((event.target as HTMLInputElement).checked)" /> </template>
方案2:使用v-model绑定(最符合Vue开发习惯)
完全不需要手动处理事件对象,通过Vue的响应式能力自动同步复选框选中状态,代码更简洁易维护:
<script setup lang="ts"> import { ref } from 'vue' // 响应式变量同步选中状态 const isChecked = ref(false) function doThing(checked: boolean) { console.log("Do thing", checked); } </script> <template> <input type="checkbox" v-model="isChecked" @change="doThing(isChecked)" /> </template>
方案3:Vue 3.4+ 简化写法(使用defineModel)
如果项目使用Vue 3.4及以上版本,可以用defineModel语法糖省去手动声明ref的步骤,代码更精简:
<script setup lang="ts"> // 直接声明双向绑定变量,默认值为false const isChecked = defineModel<boolean>(false) function doThing(checked: boolean) { console.log("Do thing", checked); } </script> <template> <input type="checkbox" v-model="isChecked" @change="doThing(isChecked)" /> </template>
内容的提问来源于stack exchange,提问作者SimpleJ
相关产品推荐
相关产品推荐

