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>

浙公网安备 33010602011771号