《Vue2.0 条件渲染指令》

101 阅读1分钟

v-if 指令用于条件性地渲染一块内容。

GIF 2022-1-6 11-03-31.gif

<template>
  <div>
    <div class="taxon" v-if="isShow"></div>
    <button @click="changeState()">改变isShow的状态{{ isShow }}</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      isShow : true
    }
  },   
  methods : {
    changeState(){
      this.isShow = !this.isShow
    }
  }
}
</script>

<style>
.taxon{
  width: 100px;
  height: 100px;
  background-color: pink
}
</style>

根据条件展示元素的选项是 v-show 指令

GIF 2022-1-6 11-08-13.gif

<template>
  <div>
    <div class="taxon" v-show="isShow"></div>
    <button @click="changeState()">改变isShow的状态{{ isShow }}</button>
  </div>
</template>

<script>
export default {
  data(){
    return {
      isShow : true
    }
  },   
  methods : {
    changeState(){
      this.isShow = !this.isShow
    }
  }
}
</script>

<style>
.taxon{
  width: 100px;
  height: 100px;
  background-color: pink
}
</style>

v-if 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。

v-if 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。

相比之下,v-show 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。

一般来说,v-if 有更高的切换开销,而 v-show 有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用 v-show 较好;如果在运行时条件很少改变,则使用 v-if 较好。