Search code examples
javascripthtmlvue.jsdata-bindingnull-coalescing

How to efficiently display text instead of null when binding in vue.js?


In the following code site can be null, but if it is there, then company will not be null. How can I efficiently display a "-" when the site is null that scales well for 1000's of these rows?

<tr v-for="obj in objs" :key="obj.id">
  <td>{{obj.site.company.name || "-"}}</td> <!-- does not work -->
</tr>

I can make a method to do this:

methods: {
  handleNulls(obj) {
    // logic
    return "-";
  }
}

But it would be nicer if it could be done inline, or using a filter.


Solution

  • Try this :

    <tr v-for="obj in objs" :key="obj.id">
      <td v-if="obj.site !== null">{{obj.site.company.name}}</td>
      <td v-else>-</td>
    </tr>
    

    Documentation - conditional rendering