Vue3 根据相对路径加载vue组件

一、设置动态组件加载器


1、"DynamicFormLoader.vue"

<template>
  <div>
    <component :is="formComponent" v-if="formComponent" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { defineProps } from 'vue';

// 定义组件属性,要求必须提供一个字符串类型的"path"属性
const props = defineProps({
  path: {
    type: String,
    required: true
  }
});

// 使用ref创建一个名为formComponent的引用,用于存储表单组件实例
const formComponent = ref(null);

// 监听props中的"path"属性的变化,当"path"变化时,动态导入相应的表单组件
watch(() => props.path, async (newPath) => {
  // 当新的路径存在时,尝试导入对应的组件
  if (newPath) {
    try {
      // 动态导入位于@/components/forms/目录下且文件名与 newPath 相同的 Vue 组件
      const component = await import(`/${newPath}`);
      // 将导入的组件赋值给formComponent引用
      formComponent.value = component.default;
    } catch (error) {
      // 如果导入失败,打印错误信息并将formComponent设为null
      console.error(`组件导入失败: ${newPath}`, error);
      formComponent.value = null;
    }
  }
}, { immediate: true });

</script>

二、父组件


<DynamicFormLoader :path="loadedFormPath" />

 在需要的地方引入这个组件就可以了,如果想要通过相对路径的方式加载对应的vue文件只需要,对loadedFormPath 进行赋值即可

子组件的路径:src/views/form/childen.vue

相关推荐

  1. Vue3 根据相对路径vue

    2024-07-11 17:30:03       29 阅读
  2. Vue3Cron

    2024-07-11 17:30:03       18 阅读
  3. Vue3: Suspense异步组件

    2024-07-11 17:30:03       58 阅读
  4. vue3路由懒

    2024-07-11 17:30:03       38 阅读
  5. Vue3实现图片懒

    2024-07-11 17:30:03       45 阅读
  6. vue3 动态页面

    2024-07-11 17:30:03       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 17:30:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 17:30:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 17:30:03       58 阅读
  4. Python语言-面向对象

    2024-07-11 17:30:03       69 阅读

热门阅读

  1. ps导入图片的方式

    2024-07-11 17:30:03       22 阅读
  2. rust way step 8

    2024-07-11 17:30:03       23 阅读
  3. MySQL sql_safe_updates参数

    2024-07-11 17:30:03       20 阅读
  4. 表单前端怎么跳转页面:深入探索与实践

    2024-07-11 17:30:03       18 阅读
  5. Mysql中触发器的使用示例

    2024-07-11 17:30:03       21 阅读
  6. 实现前端登录注册功能(有源码)

    2024-07-11 17:30:03       22 阅读
  7. 编程语言:智能制造领域的智慧引擎

    2024-07-11 17:30:03       22 阅读
  8. 通过配置IP路由解决多网卡配置同网段IP的问题

    2024-07-11 17:30:03       23 阅读
  9. ArduPilot开源代码之OpticalFlow_backend

    2024-07-11 17:30:03       23 阅读
  10. Postman API测试覆盖率:全面评估指南

    2024-07-11 17:30:03       22 阅读