vue3 初略版使用markdown

vue3 初略版使用markdown

构造一个能够编写markdown且能解析数学公式,且有预览页面的markdown组件

第一步,katex用来解析数学公式,markded用来解析markdown语法

npm install katex markded

第二步 封装组件

<template>
  <div class="markdown-container">
    <div style="flex: 50%">
      <textarea v-model="input" class="content"  placeholder="输入 Markdown" />
    </div>
    <div style="flex: 50%">
      <div v-html="renderedMarkdown" class="markdown-content"></div>
    </div>
  </div>
</template>

<script>
import { ref, watch } from 'vue';
import { marked } from 'marked';
import katex from 'katex';
import 'katex/dist/katex.min.css';

export default {
  name: 'MarkdownEditor',
  setup() {
    const input = ref('');
    const renderedMarkdown = ref('');

    // 监听 input 的变化并渲染 Markdown
    watch(input, (newInput) => {
      renderedMarkdown.value = renderMarkdown(newInput);
    });

    function renderMarkdown(markdown) {
      // 使用 marked 解析 Markdown
      const html = marked(markdown, { breaks: true });
      // 使用 KaTeX 渲染数学公式
      return renderMath(html);
    }

    function renderMath(html) {
      // 使用正则表达式找到所有的数学公式并进行渲染
      const mathRegex = /\$([^$]+)\$/g;
      return html.replace(mathRegex, (match, math) => {
        try {
          // 尝试渲染数学公式
          return `<span class="math">${katex.renderToString(math)}</span>`;
        } catch (error) {
          // 捕获错误并返回错误信息
          return `<span class="math-error">Error rendering math: ${error.message}</span>`;
        }
      });
    }

    return {
      input,
      renderedMarkdown,
    };
  },
};
</script>

<style>
.markdown-container {
  display: flex;
  gap: 1rem;
}

.content{
  width: 100%;
  height: 500px;
}

.markdown-content {
  padding: 1rem;
  min-height: 30rem;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
}
.math {
  font-size: 1rem; /* 可以根据需要调整数学公式的大小 */
}
/*解析数学公式报错时直接显示在预览页面的提示*/
.math-error {
  color: red;
  font-weight: bold;
}
</style>


posted @   Liang2003  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示