0

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.

Colton Scottie
  • 807
  • 1
  • 8
  • 22

3 Answers3

2

I would suggest an inline if. You should check whether site is undefined and whether company is undefined:

<tr v-for="obj in objs" :key="obj.id">
  <td>{{obj.site && obj.site.company ? obj.site.company.name : '-'}}</td>
</tr>
cornelius7
  • 103
  • 5
0

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

tony19
  • 125,647
  • 18
  • 229
  • 307
Core972
  • 4,065
  • 3
  • 31
  • 45
0

You wanted to show "-" if the site is not available so I did this : (the first element of the array is null)

let app;


function appInit(){
 app = new Vue({
  el:'#app',
  data:{
   obj:[
    null,
    {site:{company:{name:"test2"}}},
    {site:{company:{name:"test3"}}}
   ]
  }
 });
}

appInit();
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="item in obj">{{item && item.site && item.site.company&& item.site.company.name ? item.site.company.name : " - "}}
    </li>
  <ul>
<div>
PhilMaGeo
  • 551
  • 6
  • 8