Ransomware0
Ransomware0

Reputation: 475

How to trim in v-if vue js

A few days, i try to trim the response value in a vue condition.

I need this, when the value is null or empty apply the condition.

<li v-if="item[0].otrodl4.trim() == ''" class="progress-step">

But I got the error

vue.js:597 [Vue warn]: Error in render: "TypeError: Cannot read property 'trim' of null"

The problem is that some values bring only whitespace and no more, that should be considered null or empty.

E.G.

enter image description here

I tried it with filters but I get the same error.

Thanks for read.

Greetings.

Upvotes: 1

Views: 1990

Answers (4)

pallavi sahni
pallavi sahni

Reputation: 95

I have tried with trim() and it is working fine. please try if this can be help to you.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
</head>
<body>
<div id="app">
<!--if only space in text it will display "hello space" else no dsplay.  -->
<p v-if="text.trim()==''">hello whitespace {{ text | trim }}</p>

</div> 
<script>
new Vue({

el: '#app',
  
  data: function() {
    return {
        text: ' '    // added only a space
    }
  }
  
 

});
</script> 
         
</body>
</html>

Upvotes: 1

Maxim Mazurok
Maxim Mazurok

Reputation: 4128

Try this:

!item || !item[0] || !item[0].otrodl4 || item[0].otrodl4.trim() == ''

Basically, you have to check that item is defined and not null. And that the first element of that array exists AND that this element has otrodl4 property.

Upvotes: 2

Kevin Moe Myint Myat
Kevin Moe Myint Myat

Reputation: 2165

This is a TypeError where the variable you are trying to manipulate is not what it is thought to be by the developer.

Always happen to a language without proper typing.

Therefore, you can do an optional chaining and check the variable is what it is supposed to be first.

ES2020 has allowed us to use optional chaining to type check.

For example,

v-if="!!item?.[0]?.otrodl4?.trim && item?.[0]?.otrodl4?.trim() == ''"

!! is a type conversion to falsy values like null or undefined or empty string to become false.

It makes sure that otrodl4 has a property method trim before calling the method and therefore won't cause TypeError anymore.

Upvotes: 0

Tony
Tony

Reputation: 1432

Try this:

item[0] && item[0].otrodl4.trim() == ''

So, the only time it checks if item[0].otrodl4.trim() == '' is if there's a value in the 0 index position of the item array.

It's known as a short-circuit conditional and you can read all about it here.

Upvotes: 1

Related Questions