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

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

Posted by: admin November 26, 2021 Leave a comment

Questions:

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.

Answers:

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>

###

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

###

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>