技术咨询、项目合作、广告投放、简历咨询、技术文档下载 点击这里 联系博主

# vue3使用jsx渲染动态组件

有些使用当使用 SFC 的方式编写 vue 文件不满足需求的时候,我们会选择使用 jsx 的语法进行编写; 但是当在 jsx 中使用<component is></component>渲染组件是会发现,根本无法渲染成功;由此我们需要进行一些改变.

# 渲染局部动态组件

如果你要渲染的动态组件为局部的方式,比如:

import { PhotoStory, VideoStory } from "./stories";

const components = {
  photo: PhotoStory,
  video: VideoStory,
};

function Story(props) {
  // 正确!JSX 标签名可以为大写开头的变量。
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}

此时需要注意,组件名SpecificStory必须是大写开头;

# 渲染全局动态组件

渲染全局动态组件无法直接使用字符串的方式渲染组件,需要搭配 h函数resolveComponent

The render function cannot render global components #1927 (opens new window)

进行如下操作:

import {
  defineComponent,
  computed,
  reactive,
  PropType,
  toRefs,
  h,
  nextTick,
  resolveComponent,
  ref,
} from "vue";

/**
 * 通过左侧的组件列表拖入的组件信息获取 某个基础组件完整的schema信息
 */
export default defineComponent({
  name: "wrapper-component",
  props: {
    modelValue: Object as PropType<any>,
  },

  setup(props, { emit }) {
    // ....

    return () => {
      const DynamicComponent = resolveComponent(state.schemaInfo?.type || "");
      return (
        <div
          class={
            isActiveCurrent
              ? " wrapper-component is-active"
              : "wrapper-component"
          }
          onClick={onChangeCurrent}
        >
          {DynamicComponent
            ? //   动态组件需要使用h进行渲染
              h(DynamicComponent, {}, () => {})
            : null}
        </div>
      );
    };
  },
});
【未经作者允许禁止转载】 Last Updated: 2/4/2024, 6:06:40 AM