typescript非空断言(!)

本文介绍了在Vue3+TS项目中如何使用非空断言符(!)。在Vue的`onMounted`生命周期钩子中,由于组件已渲染完成,可以确保`child.value`不为空,因此使用非空断言符避免类型检查错误,调用`queryList`方法和设置`isShowDialog`属性。通过这个例子,读者可以了解到在何时以及为何使用TS的非空断言符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 前提:
    1、环境:在vue3+ts项目下
    2、参考资料:
    https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-

  • 原因:
    看到ts中的!非空断言符,不是特别了解就查了些资料

  • 目的:
    了解该符号作用,什么情况下使用

  • 相关代码
<template>
    <div>
      <Child
        ref="child"
      />
    </div>
</template>
<script lang="ts">
  import {defineComponent,onMounted,ref} from 'vue'
  import Child from '@/components/child.vue';
  export default defineComponent({
    components:{
      Child
    },
    setup(){
      const child = ref<typeof Child>()
      //这是TypeScript的语法,叫非空断言操作符(non-null assertion operator),和?.相反,这个符号表示对象后面的属性一定不是null或undefined。

      onMounted(async()=>{
      //这个生命周期已经渲染完成元素,所以一定是不为空的所以用了非空断言防止报错
        await child.value!.queryList()
        child.value!.isShowDialog = true
      })
      return {
        child
      }
    }
  })
</script>
<style  scoped>
.class-name-from-father{
  width: 100px;
  height: 100px;
  background-color: green;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值