问号(?.
)是 JavaScript 中的可选链操作符(Optional Chaining Operator)。它的作用是安全地访问嵌套对象的属性,避免因为某个中间属性为 null
或 undefined
而导致代码报错。
-
在访问嵌套对象属性时,如果某个中间属性为
null
或undefined
,传统的点运算符(.
)会抛出错误。 -
使用可选链操作符(
?.
)时,如果某个中间属性为null
或undefined
,表达式会直接返回undefined
,而不会抛出错误。
示例:
<div class="title">{{hospitalStore.hospitalInfo.hospital?.hosname}}</div>
-
hospitalStore.hospitalInfo.hospital?.hosname
表示:-
先访问
hospitalStore.hospitalInfo.hospital
。 -
如果
hospitalStore.hospitalInfo.hospital
为null
或undefined
,则整个表达式返回undefined
。 -
如果
hospitalStore.hospitalInfo.hospital
存在,则继续访问hosname
属性。
-
为什么使用可选链操作符?
-
在 Vue 模板中,数据可能是异步加载的,初始时
hospitalStore.hospitalInfo.hospital
可能为null
或undefined
。 -
如果不使用可选链操作符,直接访问
hospitalStore.hospitalInfo.hospital.hosname
可能会导致运行时错误。 -
使用可选链操作符可以避免这种错误,使代码更健壮。