一、动态组件
动态切换组件
代码如下(示例):
<template>
<ul>
<li v-for="(item,index) in list" :key="index" @click="change(index)">{{item.name}}</li>
</ul>
<keep-alive>
<component :is="currentComponent.com"></component>
</keep-alive>
</template>
<script setup>
import CommonC from '../components/CommonC.vue'
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'
let list = reactive([
{name:"切到A",com:markRaw(CommonA)},
{name:"切到B",com:markRaw(CommonB)},
{name:"切到C",com:markRaw(CommonC)}
])
let currentComponent = reactive({
com:list[0].com
})
const change=(idx)=>{
currentComponent.com = list[idx].com
}
</script>
1.markRaw
标记一个普通对象,使得它不可以被转换成响应式对象。简单来说,就是组件不需要响应式,这样可以提高性能。
2.keep-alive
组件在非活动状态,依旧保持组件的实例。即组件被切换时,状态不会被重置。
当一个组件实例从 DOM 中移除但它是由 缓存的组件树的一部分时keepalive,它会进入停用状态而不是被卸载。当组件实例作为缓存树的一部分插入 DOM 时,它会被激活。
保持活动状态的组件可以使用onActivated()和为这两种状态注册生命周期钩子onDeactivated()
二、异步组件
1.使用官方提供的defineAsyncComponent()函数
代码如下(示例):
<template>
<common-a></common-a>
<common-b></common-b>
<div>
//C组件为图片资源
<common-c></common-c>
</div>
</template>
<script setup>
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'
const CommonC = defineAsyncComponent(() =>
import('../components/CommonC.vue')
)
</script>
我们可以看到视口还没加载到img就直接加载出来了。
2.使用插件vueuse
代码如下(示例):
<template>
<common-a></common-a>
<common-b></common-b>
<div ref="target">
<common-c v-if="targetIsVisible"></common-c>
</div>
</template>
<script setup>
import { useIntersectionObserver } from '@vueuse/core'
// import CommonC from '../components/CommonC.vue'
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'
const CommonC = defineAsyncComponent(() =>
import('../components/CommonC.vue')
)
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
console.log(isIntersecting);
if(isIntersecting){
targetIsVisible.value = isIntersecting
}
},
)
</script>
isIntersecting 可以判断组件是否出现在视口,初始值为false,当组件出现在视口就会加载其组件。
异步组件在不使用插件的情况下,他会按需加载组件需要的js文件