Search code examples
vue.jsconditional-operatorvue-props

Vue.js ternary expression vs v-show


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!


Solution

  • 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.