Search code examples
javascripttemplatesvue.jsnullundefined

How to display space instead undefined and null in vue.js template?


This is Vue.js template

<strong>{{userdata.phone}}</strong>

When userdata.phone == null or userdata.phone == undefined, I would like to show space. for example

<strong> {{ userdata.phone | !null | !undefined }} </strong>

Is it possible? And in this case how do that?

<strong>{{userdata.location.city + userdata.location.state + userdata.location.country }}</strong>

userdata.locationi.city,state,country can be null or undefined


Solution

  • The solution is the same as having a default fallback for values in regular Javascript.

    <strong>{{ userdata.phone || " " }}</strong>
    

    The same solution works for multiple fallbacks.

    <strong>{{ userdata.location.city || userdata.location.state || userdata.location.country || " " }}</strong>
    

    Alternatively, it can be handy to use a computed property for this if there's more complex logic involved or when you want to reuse it:

    computed: {
      phone: function () {
        return this.userdata.phone || " ";
      }
    }
    

    If you're only targeting browsers that support nullish coalescing or use a build step that transpiles it for you, that's usually preferable.

    <strong>{{ userdata.phone ?? " " }}</strong>