// Vue 3 动态加载组件示例代码
<template>
<div>
<!-- 使用动态组件 -->
<component :is="currentComponent"></component>
<!-- 切换组件按钮 -->
<button @click="loadComponent('ComponentA')">Load Component A</button>
<button @click="loadComponent('ComponentB')">Load Component B</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
// 定义当前显示的组件
const currentComponent = ref(null);
// 定义动态加载组件的方法
const loadComponent = async (componentName) => {
let component;
if (componentName === 'ComponentA') {
// 动态导入 ComponentA
component = await import('./components/ComponentA.vue');
} else if (componentName === 'ComponentB') {
// 动态导入 ComponentB
component = await import('./components/ComponentB.vue');
}
// 更新当前显示的组件
currentComponent.value = component.default;
};
return {
currentComponent,
loadComponent,
};
},
};
</script>
模板部分:
<component :is="currentComponent">
:使用 :is
绑定属性来动态切换组件。<button>
按钮用于触发组件的加载,点击按钮后会调用 loadComponent
方法并传入组件名称。脚本部分:
const currentComponent = ref(null);
:定义一个响应式的变量 currentComponent
,用于存储当前要显示的组件。const loadComponent = async (componentName) => { ... }
:定义一个异步方法 loadComponent
,根据传入的组件名称动态导入相应的组件,并更新 currentComponent
的值。await import('./components/ComponentA.vue');
和 await import('./components/ComponentB.vue');
:使用 ES6 的动态导入语法 (import()
) 来按需加载组件,这样可以实现懒加载,提升应用性能。通过这种方式,你可以在需要时才加载组件,从而优化应用的加载时间和资源使用。
下一篇:vue响应式布局
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站