Home > Software engineering >  vuejs expression that has an or operator to check if property is found
vuejs expression that has an or operator to check if property is found

Time:03-19

I am using vuejs and I have an expression where I want to check to see if the name comes from either FilterName or FilterName2 by using the expression only. I do not want to use a computed property. Is there a way to write this with just expression

 
 new Vue({
  el: "#app",
  data: {
   FilteredName:""
   FilteredName2:"XX_110_OY_M10"

  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>

 {{FilteredName || FilteredName2   "_"   "_DEVELOPMENT" }}
 
 </p>
 
 </div>

CodePudding user response:

Nullish Coalescing Operator vs OR Operator

If one of them is guaranteed to be null, undefined, 0 or an empty string (""), then || operator would work exactly the same way as the Nullish coalescing operator in your case.

The OR || Operator is better to use in your case since it works the same (for this case) and has better support than nullish coalescing, due to the latter being released in 2020, so older browsers do not support it.

You just have to use it with brackets for clarity:

{{ (FilteredName || FilteredName2)   "_"   "_DEVELOPMENT" }}

The important difference between them is that:

|| returns the first truthy value.

?? returns the first defined value.

Read more: https://javascript.info/nullish-coalescing-operator

CodePudding user response:

If either of them are guaranteed to be null, I'd use the nullish coalescing operator.

(FilteredName ?? FilteredName2)   "_"   "_DEVELOPMENT"
  • Related