vue项目中展示markdown文件(markdown-it-vue)

//安装依赖
npm i markdown-it-vue

//引入markdown-ite-vue
import MarkdownItVue from "markdown-it-vue";
import "markdown-it-vue/dist/markdown-it-vue.css";

//注册组件
 components: {
        MarkdownItVue
},

//使用组件
<markdown-it-vue class="md-body" :content="htmlMD" />

//将.md文件转化为markdown-it-vue可以解析的字符串
loadMarkdown()方法

//完整代码
<template>
  <div class="md-content">
    <markdown-it-vue class="md-body" :content="htmlMD" />
  </div>
</template>
<script>
import MarkdownItVue from "markdown-it-vue";
import "markdown-it-vue/dist/markdown-it-vue.css";
export default {
    components: {
        MarkdownItVue
    },
    data(){
      return{
        htmlMD: "",
      }
    },
    methods:{
    loadMarkdown() {
		    // 假设您有一个本地markdown文件路径
		    const markdownPath = '/static/test.md'
            //通过fetch请求将.md文件转化为markdown-it-vue可以解析的字符串
		    fetch(markdownPath)
			    .then(response => response.text())
			    .then(markdown => {
                    //实验highlight未生效
				    // const md = new MarkdownIt({
					//     html: true,
					//     linkify: true,
					//     typographer: true,
					//     highlight: function (str, lang) {
					// 	    if (lang && hljs.getLanguage(lang)) {
					// 		    try {
					// 			    return hljs.highlight(lang, str).value;
					// 		    } catch (e) { }
					// 	    }
					//
					// 	    return ''; // use external default escaping
					//     }
				    // });
				    // this.markdownContent = md.render(markdown);
                    
                    //此处的markdown即为字符串
				    this.htmlMD = markdown
			    })
			    .catch(error => {
				    console.error('Error loading markdown:', error);
			    });
	    }
    },
    created(){
      this.loadMarkdown()
    }
}
</script>
posted @   Code_Lzh  阅读(1369)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示