动态组件、keep-alive、异步组件
一、动态组件:
1、组件的渲染需要依赖用户的操作而决定。
2、由vue提供的内置组件<component is="xx"><component>作为容器.
3、在component 标签里面写子组件的prop。
<template>
<div>
<div>
<a v-for="c in 3" @click="tab(c)"></a>
</div>
<component :is="currentC"></component>
</div>
</template>
<script setup>
import {ref} from "vue"
import c1 from "./components/comp1"
import c2 from "./components/comp2"
import c3 from "./components/comp3"
const currentIndex=ref(1)
function tab(c){
currentIndex.value=c;
}
const currentC=computed(()=>"c"+currentIndex.value)
</script>
二、 keep-alive:是vue提供的内置组件
在切换组件时
1、缓存组件;
2、保持组件的状态;
3、解决反复创建组件导致性能问题。
用法:用keep-alive包裹组件,
1、提供include和exclude两个prop,选择需不需要缓存的组件,默认是include。
2、提供max属性,限制最大缓存组件数量,如果超出最大值,则最久没有被渲染的组件会销毁。
3、组件的切换会执行相应的钩子函数 activated (显示)和 deactivated (隐藏)
4、activated
在组件挂载时也会调用,并且 deactivated
在组件卸载时也会调用。
5、这两个钩子不仅适用于 <KeepAlive>
缓存的根组件,也适用于缓存树中的后代组件。
<keep-alive>
<component :is="currentC"></component>
</keep-alive>
三、异步组件
静态导入模块:
import xx from './xx.js',
异步导入模块:
import('./xx.js').then(resp=>{
//resp 是一个module
)
let flag = true;
if (flag) {
import('./utils.js').then(mod => {
let { plus, minus } = mod;
console.log(plus(1, 2));
console.log(minus(1, 2));
})
}
async function getModule() {
try{
let mod = await import("./utils.js")
let { plus, minus } = mod;
console.log(plus(1, 2));
console.log(minus(1, 2));
}catch(e){
console.log(e);
}
}
if (flag) {
getModule();
}
1、import是关键字并不是方法、不是方法、不是方法。类似于typeof 、delete。
2、每一个import都会从服务器下载一个模块。
注意:import() 导入的时一个promise对象
if(typeof str ===''string) // if(tyoeof(str)==='string')
vue3中动态导入组件:
<script setup>
import {ref,defineAsyncComponent} from "vue"
const comp=defineAsyncComponent(()=>import('./xx.vue'))
</script>
vue2中动态导入组件:
<script >
export default{
components:{
comp:import('./xx.vue')
}
}
</script>
动态组件的特点:
1、按需加载组件,实现延时加载 ;
2、异步组件被分割成一个代码块,在需要的时候从服务器下载并渲染;
3、减少父组件的体积。