vue v-if和v-show的区别

126 阅读1分钟

v-if

1、不会在 vue 有虚拟 DOM,只有在条件为true时才会去编译,创建虚拟DOM再显示到页面上;为false时也会将这些DOM删除

2、如果用v-if的element ui组件有动画样式,则没有动画样式,v-show会有动画效果

3、用 v-if 显示的节点下有图片或需要从服务器加载的东西,需要等到v-if为true时才会开加载图片或从服务器加载东西(例:当数据请求完(请求时间为3 4s)才让页面显示,图片需要3 4s后才开始加载)

<div id="liveinsure" v-show="isshow == 1" :style="scheme.backgroundColor">
    <div class="bannerwrap">
      <van-image :id="scheme.logoList?'banner':''" class="banner" :src="$dtoss + banner" />
      //scheme 从配置的oss文件中获取,会很快获取到
      <van-image v-if="scheme.logoShow" class="logoimg" :src="`${$dtoss}/insure/img/logo-white.png`"></van-image>
      <van-image v-if="scheme.logo" class="logoimg" :src="`${$dtoss}/insure/img/logo.png`"></van-image>
    </div>
 </div>

4、当组件使用v-if时,从false变为true时都会触发一次生命周期

//父组件
<AgreementBind :show="agreementShow" v-show="agreementShow" :agreementData="AgreementList"
  :usingAgreementData="usingAgreementList" />
//子组件
<el-dialog :visible.sync="show" width="1000px" :before-close="cancel" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
</el-dialog>

mounted() {
    this.AgreementList = this.agreementData
    this.usingAgreementList = this.usingAgreementData
},
watch: {
//用 v-show 来控制组件时,在agreementShow为 true时 不会执行mounted,所以需要 watch 来监听数据变化
    agreementData(newVal){
        this.AgreementList = newVal
    },
    usingAgreementData(newVal) {
        this.usingAgreementList = newVal
    }
},

5、如果控制页面显示的值放在 computed 里,那页面将永远不会显示

    <el-dialog v-if="isShow">
      <el-table ref="giveTable" :data="filteredGiveList" border>
      </el-table>
    </el-dialog>
  
  computed: {
        filteredGiveList() {
            this.isShow = true // 页面有了虚拟 DOM 后才去执行 filteredGiveList
        }
    },

v-show

1、不管条件是真还是假,第一次渲染都会创建虚拟DOM

2、控制的是display的属性