Its important to understand the template syntax in vuejs is just javascript. This means any standard javascript statement will work in between the double curly braces.
The solution is to make use of Javascript's duck (dynamic) typing and to take advantage of the fact that a null or empty string also resolves to a false value.
The statement (userdata && userdata.phone) || ''
is standard javascript and works as follows
- if
userdata
is truthy (has a value) and also userdata.phone
is truthy (is not null, has a length greater than zero, and some caveats), then this side of the ||
operator is true, so return this value
- else the
||
is false, use this empty string literal ''
This may clutter up your template and you may prefer to place this in a computed property like so
<strong>{{userPhone}}</strong>
and
computed: {
userPhone() {
return (userdata && userdata.phone) || '';
}
}
You will almost certainly want to follow a computed property strategy for the location. Note that a null
value will return 'null'
when used as part of string concatenation.
computed: {
userLocation() {
if (!userdata || !userdata.location) return '';
return (userdata.location.city || '') + (userdata.location.state || '') + (userdata.location.country || '');
}
}
A more concise option could be to use the join
function of an array, which will ignore null
or undefined
values:
computed: {
userLocation() {
if (!userdata || !userdata.location) return '';
return [userdata.location.city, userdata.location.state, userdata.location.country].join(' ');
}
}