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

被折叠的 条评论
为什么被折叠?



