vue2的component的is属性可以是和组件名对应的字符串,vue3不行,必须传一个组件实例
<template> <div class="wrap"> <div class="contain"> <div class="left">111</div> <div class="right"> <component :is="currentComp"></component> </div> </div> </div> </template> <script setup lang="ts"> import { computed, shallowRef, watch } from 'vue' import { useRoute } from 'vue-router' const route = useRoute() const compName = computed(() => { return route.path.split('/').pop()?.toLowerCase() || '' }) const currentComp = shallowRef<any>(null) // 动态加载组件方法 const loadComponent = async () => { try { currentComp.value = null // 动态导入组件(假设组件在相同目录) const module = await import( /* @vite-ignore */ `./${compName.value}.vue` ) currentComp.value = module.default } catch (e) { console.error('组件加载失败:', e) currentComp.value = null } } // 监听路由变化 watch(compName, loadComponent, { immediate: true })
vue3根据路由路径动态匹配组件
最新推荐文章于 2025-04-04 22:21:28 发布