vue动态组件

36 阅读1分钟

动态组件

<template>
  <component :is="currentComponent" v-bind="passedProps"></component>
</template>

<script>
export default {
  props: {
    load: Function,
    props: Object,
  },
  data() {
    return {
      currentComponent: null, // 用于存储加载的组件
      loadedComponent: null, // 可选,用于缓存已加载的组件
    };
  },
  computed: {
    // 计算属性,用于将父组件的 props 传递给子组件
    passedProps() {
      return this.props;
    },
  },
  watch: {
    // 监听 load 函数的变化(如果 load 是响应式的或可能改变)
    // 注意:如果 load 函数不会改变,这部分可以省略
    load(newLoad, oldLoad) {
      // 当 load 函数变化时,重新加载组件
      this.loadComponent(newLoad);
    },
  },
  methods: {
    loadComponent(loadFunc) {
      // 使用 load 函数加载组件
      loadFunc()
        .then((component) => {
          // 假设 load 函数返回一个 Promise,该 Promise 解析为组件的定义
          if (!component.default) {
            console.error("Loaded module does not contain a default export");
            this.currentComponent = null; // 或设置为错误提示组件
            return;
          }
          this.currentComponent = component.default;
          // 可选:缓存已加载的组件
          // this.loadedComponent = this.currentComponent;
        })
        .catch((err) => {
          console.error("Failed to load component:", err);
          // 可以设置为错误提示组件或其他备用组件
          this.currentComponent = null; // 或设置为错误组件
        });
    },
  },
  mounted() {
    // 组件挂载后,立即加载组件
    this.loadComponent(this.load);
  },
};
</script>