如何在方法中使用导入的组件-Vue 3

7tofc5zh  于 2023-04-07  发布在  Vue.js
关注(0)|答案(1)|浏览(138)

这里我试图在splitContent方法中呈现HighlightJs组件。但是它不工作,而是将组件名称显示为html标记。我还尝试注册它有一个全局组件,仍然不起作用。

<script setup lang="ts">
import HighlightJs from "./components/HighlightJs.vue";

const splitContent: (content: string) => string = (content) => {
  const paragraphs = content.split("\n\n");
  const codeBlocks = content.split("```");

  if (codeBlocks.length > 1) {
    return codeBlocks
      .map((codeBlock, i) => {
        if (i % 2 === 0) {
          return `<p>${codeBlock}</p>`;
        } else {
          return `<HighlightJs code="${codeBlock}"></HighlightJs>`; // component is not rendered
        }
      })
      .join("");
  } else {
    return paragraphs.map((paragraph) => `<p>${paragraph}</p>`).join("");
  }
};
</script>

<template>
  <div
      class="bg-gray-500 text-white p-4 rounded-lg prose"
      v-html="splitContent(content.answer)"
  ></div>
</template>
2vuwiymt

2vuwiymt1#

好吧,我已经解决了,通过对splitContent方法进行一些更改(即,而不是加入并返回html字符串。我返回了字符串,对象组合的数组),并删除了Estus Flask在评论中建议的v-html的使用。

<script setup lang="ts">

import HighlightJs from "./components/HighlightJs.vue";

const splitContent: (content: string) => any = (content) => {
  const paragraphs = content.split("\n\n");
  const codeBlocks = content.split("```");

  if (codeBlocks.length > 1) {
    return codeBlocks.map((codeBlock, i) => {
      if (i % 2 === 0) {
        return `${codeBlock}`;
      } else {
        return {
          codeBlock,
        };
      }
    });
  } else {
    return paragraphs.map((paragraph) => `${paragraph}`);
  }
};

和模板部分

<template>
  <div class="bg-gray-500 text-white p-4 rounded-lg prose">
     <template
         v-for="(block, index) in splitContent(content.answer)"
         :key="index"
     >
        <component
            v-if="block instanceof Object"
            :is="HighlightJs"
            :code="block.codeBlock"
        />
        <p v-else>{{ block }}</p>
     </template>
  </div>
</template>

相关问题