[Vuejs]-How to use imported component inside a method – Vue3

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>

Leave a comment