vue3中不能直接使用keep-alive
vue2 和 vue3 对于keep-alive使用方法的区别
- vue2使用方法
<transition>
<router-view></router-view>
</transition>
- vue3使用方法
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
机制
当一个组件被keep - alive
包裹时,在组件切换过程中,如果该组件被再次使用,它不会被重新创建,而是直接使用之前缓存的实例。这对于性能优化非常有帮助,特别是在频繁切换组件但组件内容不需要每次都重新加载的场景下
理解原因
Vue 3 的响应式原理和组件渲染更新机制变化,vue3禁止了vue2的那种直接用法
在 Vue 2 中,transition
组件包裹router - view
的方式是比较直接的。Vue 2 的响应式系统是基于Object.defineProperty()
来实现的。transition
组件能够相对简单地监听子组件(这里是router - view
中的组件)的插入和移除等操作
Vue 3 采用了Proxy
对象来实现响应式。这使得组件的渲染和更新过程在内部机制上有所改变。Vue 3 更加注重组合式 API 和组件之间的逻辑复用,通过v - slot
获取router - view
中的组件,更好地在外部组件中对内部组件进行状态管理、事件处理等操作
下面代码可以进行测试
APP.vue
<template>
<div>
<router-link to="/HelloWorld">2222</router-link>
</div>
<div>
<router-link to="/hello2">1111</router-link>
</div>
<keep-alive>
<router-view></router-view>
</keep-alive>
<!-- <router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view> -->
</template>
router.js
import { createRouter, createWebHistory } from 'vue-router';
import HelloWorld from '../components/HelloWorld.vue';
import hello2 from '../components/hello2.vue';
const routes = [
{
path: '/HelloWorld',
component: HelloWorld,
},{
path: '/hello2',
component: hello2,
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
组件一:HelloWorld.vue
<script setup>
import { ref } from 'vue'
import { onBeforeMount,onMounted,onBeforeUnmount,onUnmounted,onActivated,onDeactivated} from 'vue'
onBeforeMount(()=>{
console.log('22222-beforeMount')
})
onMounted(()=>{
console.log('2222-mounted')
})
onBeforeUnmount(()=>{
console.log('22222 -beforeUnmount')
})
onUnmounted(()=>{
console.log('22222-unmount')
})
onActivated(()=>{
console.log('22222-activated')
})
onDeactivated(()=>{
console.log('22222-deactivated')
})
const count = ref(0)
</script>
<template>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
</div>
</template>
组件二:hello2.vue
<script setup>
import { ref } from 'vue'
import { onBeforeMount,onMounted,onBeforeUnmount,onUnmounted,onActivated,onDeactivated} from 'vue'
onBeforeMount(()=>{
console.log('111111-beforeMount')
})
onMounted(()=>{
console.log('11111-mounted')
})
onBeforeUnmount(()=>{
console.log('11111 -beforeUnmount')
})
onUnmounted(()=>{
console.log('11111-unmount')
})
onActivated(()=>{
console.log('111111-activated')
})
onDeactivated(()=>{
console.log('111111-deactivated')
})
const count = ref(0)
</script>
<template>
<div class="card">
<button type="button" @click="count++">xxxxx is {{ count }}</button>
</div>
</template>