条件渲染
1. v-if
(1)写法:
- v-if=“表达式”
- v-else-if=“表达式”
- v-else=“表达式”
(2)适用于: 切换频率较低的场景
(3)特点: 不显示的元素会直接从DOM树中移除
(4)注意: v-if、v-else-if、v-else可以一起使用,逻辑与js中if-else语句相同,但“结构”不能被打断。
<body>
<div id="root">
<h1>n = {{n}}</h1>
<button @click="n++">n+1</button>
<h1 v-if="n === 1">hello,{{name1}}</h1>
<h1 v-else-if="n === 2">hello,{{name2}}</h1>
<h1 v-else-if="n === 3">hello,{{name3}}</h1>
<h1 v-else-if="n === 4">hello,{{name4}}</h1>
<h1 v-else=>hello,BlackPink</h1>
</div>
<script>
Vue.config.productionTip = false
const vm = new Vue({
el:'#root',
data: {
n: 0,
name1: 'Jisoo',
name2: 'Jennie',
name3: 'Rose',
name4: 'Lisa',
}
})
</script>
</body>
2. v-show
(1)写法: v-show=“表达式”
(2)适用于: 切换频率高的场景
(3)特点: 不显示的元素不会从DOM树中移除,只是在样式上隐藏
<body>
<div id="root">
<h1>n = {{n}}</h1>
<button @click="n++">n+1</button>
<h1 v-show="n === 1">hello,{{name1}}</h1>
<h1 v-show="n === 2">hello,{{name2}}</h1>
<h1 v-show="n === 3">hello,{{name3}}</h1>
<h1 v-show="n === 4">hello,{{name4}}</h1>
</div>
<script>
Vue.config.productionTip = false
const vm = new Vue({
el:'#root',
data: {
n: 0,
name1: 'Jisoo',
name2: 'Jennie',
name3: 'Rose',
name4: 'Lisa',
}
})
</script>
</body>
备注
v-if可能会获取不到元素,v-show一定可以获取到元素。