vue3 按需加载组件
子组件.vue <template> <div> <p>这个组件按需加载</p> <h1>这个组件显示</h1> </div> </template>
<template> <div class="father"> <el-button text @click="openHadndler"> 打开 </el-button> <TestCom v-if="showwFlag" title="父组件给的标题" aa="我是aa" bb="我是bb"></TestCom> </div> </template> <script setup lang="ts"> import { defineAsyncComponent, ref } from 'vue' const TestCom = defineAsyncComponent(() => import('../../components/TestCom.vue')) let showwFlag=ref(false) const openHadndler = () => { showwFlag.value=true } </script>
好几个组件按需加载
const 组件名1 = defineAsyncComponent(() => import('组件路径1')) const 组件名2 = defineAsyncComponent(() => import('组件路径2')) const 组件名3 = defineAsyncComponent(() => import('组件路径3'))
vue2 按需加载组件
components:{ testcom:()=>import('../components/test-com') }
以下是对变化的高层次概述:
新的 defineAsyncComponent 助手方法,用于显式地定义异步组件 component 选项重命名为 loader Loader 函数本身不再接收 resolve 和 reject 参数,且必须返回一个 Promise
在 Vue 3 中
import { defineAsyncComponent } from 'vue' import ErrorComponent from './components/ErrorComponent.vue' import LoadingComponent from './components/LoadingComponent.vue' // 不带选项的异步组件 const asyncPage = defineAsyncComponent(() => import('./NextPage.vue')) // 带选项的异步组件 这个带选项的平时应该是使用的较少的 const asyncPageWithOptions = defineAsyncComponent({ loader: () => import('./NextPage.vue'), delay: 200, timeout: 3000, errorComponent: ErrorComponent, loadingComponent: LoadingComponent })