<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>
<p>该代码使用 Uniapp 的 'rich-text' 组件来显示富文本。在 'convertToRichTextNodes' 方法中,使用正则表达式匹配并替换 Markdown 语法,最终返回一个包含 'type' 为 'html','text' 为处理后的 HTML 字符串的对象数组。样式中对引用部分进行特殊处理,使其看起来像一个聊天气泡。</p>
Uniapp Markdown 高亮聊天框实现方法

原文地址: https://www.cveoy.top/t/topic/mzm6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录