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



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

<script setup lang="ts">
import HighlightJs from "./components/HighlightJs.vue";
const splitContent: (content: string) => string = (content) => {
const paragraphs = content.split("nn");
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>

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

<script setup lang="ts">
import HighlightJs from "./components/HighlightJs.vue";
const splitContent: (content: string) => any = (content) => {
const paragraphs = content.split("nn");
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>

最新更新