Home > Software design >  Vue.js ternary expression vs v-show
Vue.js ternary expression vs v-show

Time:10-08

I have to change icon type play/pause conditionally, passing it via props.

In such case should I use the ternary expression in order to pass correct prop?

<my-icon :icon="!isPlaying ? 'play' : 'pause'"></my-icon>

Or it would be better to use v-show to achieve the best performance?

<my-icon v-show='!isPlaying' :icon='play'></my-icon>
<my-icon v-show='isPlaying' :icon='pause'></my-icon>

Thank you in advance!

CodePudding user response:

A better approach would be removing the v-if and sending the different values to icon prop using computed

<my-icon :icon="getIcon"></my-icon>
export default {
 computed: {
  getIcon() {
   return isPlaying?'pause':'play':
  }
 }
}

Through the above method, you can send any values based on the different conditions with having one short line of code in the template section

CodePudding user response:

TLDR: Either should be fine and the resulting performance difference should be negligible.

Additional Thoughts:

Performance wise, I would imagine that the difference in time to render would be negligible. As a personal preference, the usage of the first one seems more appealing to me as it only inserts one <my-icon /> element into the DOM rather than two and hiding one.

As an alternative to v-show, you could use the v-if conditional directive to not even render the element that won't be displayed in the DOM for example two above. This would result in only one in the DOM at a time similar to example one. Below is the usage for v-if:

<my-icon v-if='!isPlaying' :icon='play'></my-icon>
<my-icon v-if='isPlaying' :icon='pause'></my-icon>

While this is probably slightly more performant than v-show since the second non-displaying element doesn't have to be added to the DOM, the difference again is probably negligible.

  • Related