Vue.js - Conditional rendering
Section3
by hyeyoon
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<!-- v-if의 경우 엘리먼트를 DOM에서 지우거나 생성 (attach or dettach)-->
<p v-if="show">You can see me!</p>
<p v-else>Now you see me!</p>
<!-- template은 html5 코드로 dom에는 렌더링되지 않는다 -->
<!-- 여러개의 엘리먼트를 보여주고 숨길 때 template을 사용하면 유용 -->
<template v-if="show">
<p>Inside template code</p>
</template>
<!-- v-show의 경우 style의 display 속성을 none을 추가하는 효과, dom에서 사라지지 않음 -->
<!-- v-show always compiles and renders everything - it simply adds the "display: none" style to the element. It has a higher initial load cost, but toggling is very cheap.
Incomparison, v-if is truely conditional: it is lazy, so if its initial condition is false, it won't even do anything. This can be good for initial load time. When the condition is true, v-if will then compile and render its content. Toggling a v-if block actually tearsdown everything inside it, e.g. Components inside v-if are acually destroyed and re-created when toggled, so toggling a huge v-if block can be more expensive than v-show.
So when to use which really depends on the scenario. -->
<p v-show="show">Do you also see me?</p>
<button @click="show = !show">Switch</button>
</div>
JavaScript
new Vue({
el: '#app',
data: {
show: true
}
})