Mixing optional chaining with the nullish coalescing operator could be the solution you need for your situation.
computed() {
isVerified() {
return this.name?.info?.is_valid ?? false;
}
}
If any of this.name
, this.name.info
, or this.name.info.is_valid
is either null
or undefined
, isVerified
will output false
(as a boolean). However, if all properties are defined, it will return the current value of this.name.info.is_valid
, regardless of its falsy nature (excluding only null
or undefined
, so values like 0
, ''
, NaN
are considered).
Remember that at this moment, the following browsers do not support both operators:
- Internet Explorer
- Firefox for Android
- Opera for Android
- Samsung Internet
To check their current compatibility status, visit caniuse.com:
When using the latest Vue 2 version (v2.6.11
): both operators can only function inside components (such as methods, computed properties, hooks, etc.), problems may arise when directly used in templates.
While I haven't tested them on Vue 3, they should be supported (as they're recognized TypeScript operators in v3.7).
For those interested, here is the result of:
function isValid(name) {
return name?.info?.is_valid ?? false;
}
...when processed by Babel:
"use strict";
function isValid(name) {
var _name$info$is_valid, _name$info;
return (_name$info$is_valid = name === null || name === void 0
? void 0
: (_name$info = name.info) === null || _name$info === void 0
? void 0
: _name$info.is_valid
) !== null && _name$info$is_valid !== void 0
? _name$info$is_valid
: false;
}