vue异步导入
vue的异步导入
大家开发vue的时候或多或少路由的异步导入 component: () =>import(“@/views/A_centerControl/intelligent-control/access-user-group”),当然这是路由页面,那么组件也是可以异步导入的
使用方式
组件的异步导入非常简单,主要是一个api :defineAsyncComponent
先看看官方用法
import { defineAsyncComponent } from 'vue'const AsyncComp = defineAsyncComponent(() =>import('./components/MyComponent.vue')
)
用法是比较简单的
那现在我们整个项目来实践一下
区别
首先,我们看看如果不用异步导入的话,页面组件会是什么样子的
<template><div>indexVue</div><sync-index></sync-index>
</template>
<script setup>
import SyncIndex from './component/SyncIndex.vue';
</script>
<style lang="scss" scoped></style>
此时页面显示
,
然后我们切换到异步加载
<template><div>indexVue</div><!-- <sync-index></sync-index> --><SyncIndex></SyncIndex>
</template>
<script setup>
import { defineAsyncComponent } from 'vue';
// import SyncIndex from './component/SyncIndex.vue';
const SyncIndex = defineAsyncComponent(() => import('./component/AsyncIndex.vue'));
</script>
<style lang="scss" scoped></style>
看起来没什么区别呀;
确实,在这种使用情况下确实没啥区别,但是,如果这个组件是通过点击某个按钮显示的呢,最经典的就是后台管理项目点击新增的弹框,那这时候我们再看一下
<template><div>indexVue</div><!-- <sync-index></sync-index> --><el-button type="primary" @click="loadingComponent">异步组件</el-button><component:is="currentComponent"v-show="isload":isPlaying@remove="remove"></component>
</template>
<script setup>
import { defineAsyncComponent } from 'vue';
// import SyncIndex from './component/SyncIndex.vue';
const currentComponent = ref();
const isload = ref(false);
const loadingComponent = () => {if (currentComponent.value) {isload.value = true;return;}currentComponent.value = defineAsyncComponent(() => import('./component/AsyncIndex.vue'),);isload.value = true;
};
</script>
<style lang="scss" scoped></style>
上面的代码是当点击的时候会加载组件,并显示组件内容,我们先看看刚进入这个页面
有聪明的小伙子已经发现了,AsyncIndex组件再网络请求中没有,那让我们点击按钮看一下结果
发现了吧,当点击按钮加载组件的时候才会去获取组件,跟我们以前的写法不一致,import SyncIndex from './component/SyncIndex.vue';
这种方式是进入这个页面的时候就会去加载组件,而异步导入是在要被加载的时候才会导入,我们这个案例就是再点击的时候加载,这其实是一种页面的优化手段
如果一个页面有一个比较复杂的弹框或者页面,只有在触发一个事件的时候才会显示,就可以使用异步导入的方式,将这个复杂组件推迟加载
等待组件显示
当网络环境不好的时候,希望有一个等待的过程
<template><div><h1>异步组件示例</h1><el-button type="primary" @click="loadComponent">加载异步组件</el-button><component :is="AsyncComp" /></div>
</template><script setup>
import { shallowRef, defineAsyncComponent } from 'vue';
import LoadingComponent from './component/Loading.vue'; // 加载组件// 定义异步组件
const AsyncComp = shallowRef();
// // 点击按钮时加载组件
const loadComponent = () => {AsyncComp.value = defineAsyncComponent({loader: () => import('./component/AsyncIndex.vue'), // 异步加载的组件loadingComponent: LoadingComponent, // 加载时显示的组件delay: 20, // 加载延迟});
};
</script><style scoped>
/* 样式 */
</style>
总结
以上就是异步导入defineAsyncComponent的用法,可能会有错误,请各位巨佬提出