조건에 따라 블록을 렌더링할 때 사용한다.
블록은 디렉티브의 표현식이 true 값을 반환할 때만 렌더링 된다.
<template>
<button @click="handler"> // 누를 때마다 count 1 증가
Click me!
</button>
<h1 v-if="isShow"> // isShow=true시 출력
Hello?!
</h1>
<h1 v-else-if="count > 3"> // count 3이상시 isShow=false시 출력
Count > 3
</h1>
<h1 v-else> // count 3까지 isShow=false시 출력
Good~
</h1>
</template>
<script>
export default {
data() {
return {
isShow: true,
count: 0
}
},
methods: {
handler() {
this.isShow = !this.isShow
this.count += 1
}
}
}
</script>
template 사용
<template>
<button @click="handler">
Click me!
</button>
<template v-if="isShow"> // 둘 이상의 엘리먼트를 전환할 때 이용하며, template은 눈에 보이지 않는 감싸는 역할을 한다.
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
</template>
<script>
export default {
data() {
return {
isShow: true,
count: 0
}
},
methods: {
handler() {
this.isShow = !this.isShow
this.count += 1
}
}
}
</script>
조건에 따라 블록을 렌더링할 때 사용하며, 단순히 엘리먼트의 CSS display 속성만을 전환한다.
<template>
<button @click="handler">
Click me!
</button>
<h1 v-show="isShow"> // display:none
Hello?!
</h1>
</template>
<script>
export default {
data() {
return {
isShow: false,
count: 0
}
},
methods: {
handler() {
this.isShow = !this.isShow
this.count += 1
}
}
}
</script>
Reference