vue项目加载md文件两种加载需求,一种是导入本地md文件渲染,一种是加载远程md文件渲染,本地导入用的是 vue-markdown-loader
导入,而远程加载用的是 markdown-it-vue
一. 本地导入
- 安装 vue-markdown-loader
yarn add vue-markdown-loader -D
- 安装 github-markdown-css、highlight.js
yarn add github-markdown-css -D
yarn add highlight.js -D
- 在vue.config.js中配置webpack
chainWebpack: (config) => {
config.module.rule('md')
.test(/\.md/)
.use('vue-loader')
.loader('vue-loader')
.end()
.use('vue-markdown-loader')
.loader('vue-markdown-loader/lib/markdown-compiler')
.options({
raw: true
})
}
- 页面引入样式
import 'github-markdown-css'
import 'highlight.js/styles/github.css'
- 使用
<template>
<div class="content">
<!-- class的值必须包含 markdown-body -->
<div class="markdown-body" style="width:40%;padding:0 20px">
<md></md>
</div>
</div>
</template>
<script>
import md from './index.md'
export default {
components :{md}
};
</script>
二. 远程加载
- 安装markdown-it-vue
cnpm i markdown-it-vue
- 使用
<template>
<div class="md-content">
<markdown-it-vue class="md-body" :content="htmlMD"/>
</div>
</template>
<script>
import axios from 'axios';
import MarkdownItVue from 'markdown-it-vue'
import 'markdown-it-vue/dist/markdown-it-vue.css'
export default {
data(){
return {
htmlMD:""
}
},
components:{
MarkdownItVue
},
created(){
axios.get("/mdFile/aa.md").then((response) => {
this.htmlMD = response.data;
console.log(this.htmlMD)
});
}
}
</script>
<style>
</style>