大量v-if的弊端
在項目中會經常遇到大量業務條件選擇的場景,如果大量使用v-if指令,會造成:
- 頁面渲染性能下降,加載時間增加:每個v-if都需要進行計算,會導致頁面初次渲染的耗時增加,延長頁面加載時間
- 冗余代碼增加:過多v-if會使template模板代碼冗長、難以維護、可讀性差、可維護性下降
- 內存增加:每個v-if都會生成對應的DOM元素,并在切換條件時進行創建和銷毀,會導致內存占用增加,對性能和資源消耗產生影
解決方案
計算屬性
通過計算屬性的返回值來控制頁面渲染
<template>
<div>
<span v-if="content">{{ content }}</span>
</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue'
const content= computed(() => {
if (/* 1 */) {
return 'content 1'
} else if (/* 2 */) {
return 'content 2'
} else {
return 'content 3'
}
})
</script>
動態異步組件
使用<component :is="component"></component> 動態切換組件
<template>
<div>
<component :is="component"></component>
</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue'
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
import ComponentC from './ComponentC.vue'
const currentComponent = computed(() => {
if (/* 1 */) {
return ComponentA
} else if (/* 2 */) {
return ComponentB
} else {
return ComponentC
}
})
</script>
v-show
頻繁切換元素的顯示和隱藏時,可以使用v-show代替v-if
<template>
<div>
<span v-show="visible">content</span>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const visible= ref<boolean>(true)
</script>