【操作】vue-markdown使用

4,236 阅读1分钟

本文已参与好文召集令活动,点击查看:后端、大前端双赛道投稿,2万元奖池等你挑战!

引入vue-markdown

npm 安装

npm install --save vue-markdown

引入github-markdown-css

npm 安装

npm install github-markdown-css

导入github-markdown.css文件

import 'github-markdown-css/github-markdown.css

并设置markdoen-body样式

.markdown-body {
    box-sizing: border-box;
    min-width: 200px;
    max-width: 980px;
    margin: 0 auto;
    padding: 45px;
}
 
@media (max-width: 767px) {
    .markdown-body {
        padding: 15px;
    }
}

感谢作者:github: https://github.com/sindresorhus/github-markdown-css

完整代码写法

<!--
 * @Description: 渲染markdown文件
 -->
<template>
  <div id="my-markdown" class="markdown-body">
    <vue-markdown :source="md"></vue-markdown>
  </div>
</template>
<script>
import VueMarkdown from "vue-markdown";
export default {
  name: "MyMarkdown",
  components: {
    VueMarkdown
  },
  data() {
    return {
      md: ""
    };
  },
  created() {
    // 从后端请求README.md
    this.$axios
      .get("/api/public/docs/README.md", {})
      .then(res => {
        this.md = res.data.data;
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }
};
</script>
<style>
@import 'github-markdown-css/github-markdown.css';
.markdown-body {
  box-sizing: border-box;
  margin: 0 auto;
  padding: 0 40px;
}
</style>

后端接口

@RequestMapping("/api/public/docs/README.md")
    public ResT getAbout() throws IOException {
        String readme = "README.md";
        //1.获取通道
        FileInputStream fin = new FileInputStream(readme);
        FileChannel fc = fin.getChannel();

        //2.创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int length = -1;
        StringBuffer stringBuffer = new StringBuffer();
        //3.将数据从通道读到缓冲区中
        while ((length = fc.read(buffer)) != -1) {
            stringBuffer.append(new String(buffer.array()));
            buffer.clear();
        }
        fin.close();

        return ResT.ok().setData(stringBuffer.toString().trim());
    }

截图

image.png

image.png