動態(tài)組件使用keep-alive
使用setup語法糖,定義組件TestCom2
// TestCom2
<template>
<div>
<h3 class="text-lg text-blue-600 ">這是TestCom2組件</h3>
<div class="mt-2 ">
<button class="my-btn" @click="count++">+</button>
<span class="mx-2 "> {{count}} </span>
<button class="my-btn" @click="count--">-</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<style lang='scss' scope>
</style>
不使用setup語法糖,定義組件TestCom1
// TestCom1
<template>
<div>
<h3 class="text-lg text-red-600 ">這是TestCom1組件</h3>
<div class="mt-2 ">
<button class="my-btn" @click="count++">+</button>
<span class="mx-2 "> {{count}} </span>
<button class="my-btn" @click="count--">-</button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'TestCom1',
setup() {
const count = ref(0)
return {
count
}
}
})
</script>
<style scoped>
</style>
不使用setup語法糖引入組件
<template>
<div class="p-2 keep-alive">
<div class="p-2 mb-2 border-b border-gray-500">
<button class="my-btn" @click="currentCom = 'TestCom1'">組件1</button>
<button class="my-btn" @click="currentCom = 'TestCom2'">組件2</button>
</div>
<div class="p-2 border rounded-md shadow-lg">
<keep-alive include="TestCom1,TestCom2">
<component :is="currentCom"></component>
</keep-alive>
</div>
</div>
</template>
<script lang="ts">
import TestCom1 from '@/components/define/TestCom1.vue'
import TestCom2 from '@/components/define/TestCom2.vue'
import { defineComponent } from 'vue'
export default defineComponent({
components: {
TestCom1,
TestCom2
},
data() {
return {
currentCom: 'TestCom1'
}
}
})
</script>
結(jié)論:不使用setup語法糖引入組件, 不使用include 都可以實(shí)現(xiàn)緩存炬太, 使用include 后 TestCom1(沒有用語法糖) 有緩存,TestCom2(用語法糖)沒有緩存
使用setup語法糖引入組件
<template>
<div class="p-2 keep-alive">
<div class="p-2 mb-2 border-b border-gray-500">
<!-- templte中組件名稱不要帶''要不然顯示不出來 -->
<button class="my-btn" @click="currentCom = TestCom1">組件1</button>
<button class="my-btn" @click="currentCom = TestCom2">組件2</button>
</div>
<div class="p-2 border rounded-md shadow-lg">
<!-- 不適用include 可以實(shí)現(xiàn)緩存-->
<!-- include="TestCom1",TestCom1可以實(shí)現(xiàn)緩存-->
<!-- include="TestCom2",TestCom不能實(shí)現(xiàn)緩存-->
<keep-alive include="TestCom1">
<component :is="currentCom"></component>
</keep-alive>
</div>
</div>
</template>
<script setup>
import TestCom1 from '@/components/define/TestCom1.vue'
import TestCom2 from '@/components/define/TestCom2.vue'
import { ref, shallowRef } from 'vue'
const currentCom = shallowRef(TestCom1)
</script>
結(jié)論:使用setup語法糖引入組件, 不使用include 都可以實(shí)現(xiàn)緩存剔猿,使用include 后 TestCom1(沒有用語法糖) 有緩存恶导,TestCom2(用語法糖)沒有緩存
總結(jié): keepalive的include匹配首先檢查組件自身的 name 選項(xiàng)怠硼,如果 name 選項(xiàng)不可用淮摔,則匹配它的局部注冊名稱 (父組件 components 選項(xiàng)的鍵值)浑玛。匿名組件不能被匹配,所以使用setup語法糖就無法使用使用include,需要進(jìn)行取舍
最后編輯于 :2022.01.19 09:39:30
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者