0

here I am trying to render the HighlightJs component inside splitContent method. But it is not working instead it displays the Component name as a html tag. Also I tried registering it has a global component, still it doesn't work.

<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>
Manikandan
  • 502
  • 1
  • 7
  • 17

1 Answers1

0

Okay I have resolved by making some changes to the splitContent method (i.e instead of joining and returning html string. I returned array with string, object combination) and also remove the usage of v-html as suggested by Estus Flask in comment.

<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}`);
  }
};

and in template section

<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>
Manikandan
  • 502
  • 1
  • 7
  • 17