Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. VueJS offers two ways to display information conditionally with directives: `v-if` and `v-show`. `v-if` will only render to the DOM when its value evaluates to true. `v-show` will render to the DOM either way but will have inline styling to the effect of `display: none;` if its value evaluates to false.
  2.  
  3. #### `v-if`
  4.  
  5. ```vue
  6. <div class="root">
  7. <p v-if="true">Hello</p>
  8. </div>
  9. ```
  10.  
  11. renders to the DOM:
  12.  
  13. ```html
  14. <div class="root">
  15. <p>Hello</p>
  16. </div>
  17. ```
  18.  
  19. Whereas
  20.  
  21. ```vue
  22. <div class="root">
  23. <p v-if="false">Hello</p>
  24. </div>
  25. ```
  26.  
  27. renders to the DOM:
  28.  
  29.  
  30. ```html
  31. <div class="root">
  32. </div>
  33. ```
  34.  
  35. #### `v-else`
  36.  
  37. Briefly:
  38.  
  39. ```vue
  40. <div class="root">
  41. <p v-if="false">This will render if the value of v-if evaluates to true</p>
  42. <p v-else-if="true">This will render if the value of the v-else-if evaluates to true and the value of the most recent v-if evaluates to false</p>
  43. <p v-else>This will render if the value of the most recent v-if (and those of all following v-else-ifs) evaluates to false</p>
  44. </div>
  45. ```
  46.  
  47. renders to the DOM:
  48.  
  49. ```html
  50. <div class="root">
  51. <p>This will render if the value of the v-else-if evaluates to true and the value of the most recent v-if evaluates to false</p>
  52. </div>
  53. ```
  54.  
  55. #### `v-show`
  56.  
  57. ```vue
  58. <div class="root">
  59. <p v-show="true">Hello</p>
  60. </div>
  61. ```
  62.  
  63. renders to the DOM:
  64.  
  65. ```html
  66. <div class="root">
  67. <p>Hello</p>
  68. </div>
  69. ```
  70.  
  71. Whereas
  72.  
  73. ```vue
  74. <div class="root">
  75. <p v-show="false">Hello</p>
  76. </div>
  77. ```
  78.  
  79. renders to the DOM:
  80.  
  81.  
  82. ```html
  83. <div class="root">
  84. <p style="display: none;">Hello</p>
  85. </div>
  86. ```
  87.  
  88. #### Comparison
  89.  
  90. `v-show` is useful if you want to manipulate an html element while it's not shown (you can't do that with `v-if`), but it doesn't give you access to `v-else`, and having more DOM elements affects performance, so usually `v-if` is better.
  91.  
  92. `v-show` technically is also a form of in-line styling, which is a dangerous road to start down.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement