# 读取MD文件
1. 加载依赖
> markdown-loader
> html-loader
> marked
*注意事项:*
~~~json
{
// ...
// html-loader 版本过高 会报错:this.getOptions is not a function
"html-loader": "^1.0.0",
"markdown-loader": "^6.0.0"
// ...
}
~~~
【说明:】`markdown-loader`、`html-loader`是为了让`vue`能够解析`md`格式的文件,读取出来,然后使用`marked`将读取出来的数据转换成`html`格式渲染到页面上。使用`marked`是为了使用更方便。
2. 配置webpack
* vue2.x `webpack.base.conf.js`
~~~js
module: {
rules: [
...
// 配置读取 *.md 文件的规则
{
test: /\.md$/,
use: [
{ loader: 'html-loader' },
{ loader: 'markdown-loader', options: {} }
]
},
...
]
}
~~~
* vue3.x `vue.config.js`
~~~js
const path = require("path");
module.exports = {
configureWebpack: {
module: {
rules: [
...
// 配置读取 *.md 文件的规则
{
test: /\.md$/,
use: [
{ loader: "html-loader" },
{ loader: "markdown-loader", options: {} }
]
},
...
]
}
}
};
~~~
3. vue中使用
~~~html
<template>
<div>
<div>文档</div>
<div v-html="html"></div>
</div>
</template>
<script>
import MDtest from "./test.md"
export default {
data() {
return {
html: MDtest
};
}
}
};
</script>
~~~
4. 样式依赖 `github-markdown-css`
5. 引入 `import 'github-markdown-css';`
6. 绑定样式class `<div v-html="html" class="markdown-body"></div>`
# MD在线编辑
1. 依赖加载
> showdown
2. 代码测试
~~~html
<template>
<div class="edit">
<div class="edit-box">
<textarea v-model="text"></textarea>
</div>
<div class="show-box">
<div v-html="show_html" class="markdown-body"></div>
</div>
</div>
</template>
<script>
import showdown from "showdown";
const converter = new showdown.Converter();
export default {
data() {
return {
text: "# hello!"
};
},
computed: {
show_html() {
return converter.makeHtml(this.text);
}
}
};
</script>
<style scoped>
.edit {
display: flex;
height: 600px;
width: 100%;
}
.edit-box,
.show-box {
flex: 1;
height: 100%;
border: 1px solid #ddd;
box-sizing: border-box;
}
.edit-box {
margin-right: 20px;
}
textarea {
width: 100%;
height: 100%;
overflow: auto;
resize: none;
border: none;
padding: 5px;
box-sizing: border-box;
}
textarea:focus {
outline: none;
}
.show-box {
width: 100%;
height: 100%;
padding: 5px;
overflow: auto;
box-sizing: border-box;
}
~~~