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.

79 lines
1.6 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# Vue3中渲染markdown教程
### 1. 安装md插件
```shell
pnpm add marked
```
### 2. 安装美化样式
- **安装`github-markdown-css`**
```shell
pnpm add github-markdown-css
```
- **在main.js中全局引入样式如果单个页面使用可以直接页面中引入即可**
```javascript
import 'github-markdown-css/github-markdown.css'
```
- **reset.scss初始化样式中添加如下代码**
```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. 页面使用
```vue3
<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方法实现
```javascript
/** 获取远程资源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));
});
};
```