uniapp帮我写一个markdown高亮聊天框
下面是一个简单的uniapp代码,使用markdown语法来实现高亮聊天框:
<template>
<view class="chat-container">
<view v-for="(message, index) in messages" :key="index" class="message">
<rich-text :nodes="convertToRichTextNodes(message.text)" />
</view>
</view>
</template>
<script>
export default {
data() {
return {
messages: [
{ text: "Hello **world**!" },
{ text: "This is a `code` block." },
{ text: "> This is a quote." },
],
};
},
methods: {
convertToRichTextNodes(text) {
// 处理粗体、斜体、代码块、引用等markdown语法
const regexes = [
{ regex: /\*\*(.*?)\*\*/g, replace: "<b>$1</b>" },
{ regex: /__(.*?)__/g, replace: "<b>$1</b>" },
{ regex: /\*(.*?)\*/g, replace: "<i>$1</i>" },
{ regex: /_(.*?)_/g, replace: "<i>$1</i>" },
{ regex: /`(.*?)`/g, replace: "<code>$1</code>" },
{ regex: /^> (.*)$/gm, replace: "<blockquote>$1</blockquote>" },
];
let html = text;
for (const { regex, replace } of regexes) {
html = html.replace(regex, replace);
}
// 处理换行符
html = html.replace(/\n/g, "<br>");
return [{ type: "html", text: html }];
},
},
};
</script>
<style>
.chat-container {
padding: 10px;
}
.message {
margin-bottom: 10px;
}
blockquote {
margin: 0;
padding: 10px;
background-color: #f5f5f5;
border-left: 5px solid #ccc;
}
</style>
这个代码使用了uniapp的rich-text组件来显示富文本。在convertToRichTextNodes方法中,我们使用了正则表达式来匹配并替换markdown语法。最后返回的是一个包含type为html,text为我们处理后的html字符串的对象数组。在样式中,我们对引用部分进行了特殊处理,使其看起来像是一个聊天气泡。
原文地址: https://www.cveoy.top/t/topic/9wl 著作权归作者所有。请勿转载和采集!