You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1.6 KiB
1.6 KiB
Vue3中渲染markdown教程
1. 安装md插件
pnpm add marked
2. 安装美化样式
- 安装
github-markdown-css
pnpm add github-markdown-css
- 在main.js中全局引入样式(如果单个页面使用可以直接页面中引入即可)
import 'github-markdown-css/github-markdown.css'
- reset.scss初始化样式中添加如下代码
// markdown 解析格式美化
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 100%;
margin: 0 auto;
padding: 20px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
3. 页面使用
<template>
<div
class="markdown-body"
v-html="htmlStr"
/>
</template>
<script setup>
import { ref } from 'vue';
import { marked } from 'marked';
import { getMarkdownContent } from '@/utils/tools';
const htmlStr = ref('');
getMarkdownContent('./md/vue3中渲染markdown.md').then((res) => {
htmlStr.value = marked(res);
});
</script>
getMarkdownContent方法实现
/** 获取远程资源markdown内的内容 */
export const getMarkdownContent = (filePath) => {
return new Promise((resolve, reject) => {
fetch(filePath, {
method: 'GET',
})
.then((result) => {
result
.text()
.then((res) => {
resolve(res);
})
.catch((err) => reject(err));
})
.catch((err) => reject(err));
});
};