条件渲染
-
v-if (是否显示)
<template> <view> <!-- 条件渲染 --> <!-- v-if --> <view class="box" v-if="isShow" > box </view> <button type="default" @tap="changeShow()">显示/隐藏</button> <!-- v-if --> <view class="box" v-if="age>20" > {{age>30?'中年人':'年轻人'}} {{age}} </view> <button type="default" @tap="changeAge()">年龄+</button> <button type="default" @tap="changeAgem()">年龄-</button> </view> </template> <script> export default { data() { return { isShow:true, age:10 } }, methods: { changeShow:function(){ this.isShow=!this.isShow }, changeAge:function(){ this.age+=11 }, changeAgem:function(){ this.age-=11 } } } </script> <style> .box{ background: gray; color: aliceblue; font-size: 50upx; width: 350upx; height: 350upx; display: flex; justify-content: center; align-items: center; } </style>
-
v-show
<template> <view> <!-- 条件渲染 --> <!-- v-show --> <view class="box" v-show="isShow" > box </view> <button type="default" @tap="changeShow()">显示/隐藏</button> <!-- v-show --> <view class="box" v-show="age>20" > {{age>30?'中年人':'年轻人'}} {{age}} </view> <button type="default" @tap="changeAge()">年龄+</button> <button type="default" @tap="changeAgem()">年龄-</button> </view> </template> <script> export default { data() { return { isShow:true, age:10 } }, methods: { changeShow:function(){ this.isShow=!this.isShow }, changeAge:function(){ this.age+=11 }, changeAgem:function(){ this.age-=11 } } } </script> <style> .box{ background: gray; color: aliceblue; font-size: 50upx; width: 350upx; height: 350upx; display: flex; justify-content: center; align-items: center; } </style>
-
v-if和v-show的区别
v-if
1、v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。
2、v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。v-show
1、v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。总结:
相同点:1、v-if 与 v-show 都可以动态控制 DOM 元素的显示隐藏。
不同点:1、v-if 有更高的切换开销,v-show 有更高的初始渲染开销
3、v-if 适合运营条件不大可能改变;v-show 适合频繁切换。
4、v-if 通过动态向DOM树增删DOM元素,v-show 设置display来进行隐藏
5、v-if 切换有一个局部编译/卸载的过程,切换过程中合适地销毁和重建内部的事件监听和子组件;v-show 只是简单的基于 CSS 切换;
如果需要非常频繁地切换,则使用v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好。 -
官方推荐的渲染方式[ v-if v-else ]
<template> <view> <!-- 条件渲染 v-if v-else --> <template v-if="isShow"> <view class="box"> box </view> </template> <template v-else-if="age>15"> <view class="box"> {{age}} </view> </template> <template v-else> <view class="box"> {{age}} </view> </template> <button type="default" @tap="changeShow()">显示/隐藏</button> </view> </template> <script> export default { data() { return { isShow:true, age:10 } }, methods: { changeShow:function(){ this.isShow=!this.isShow this.age+=11 } } } </script> <style> .box{ background: gray; color: aliceblue; font-size: 50upx; width: 350upx; height: 350upx; display: flex; justify-content: center; align-items: center; } </style>