Vue3中使用marked展示markdown文件

1,042 阅读1分钟

markdown官方网址

www.npmjs.com/package/mar…

本次项目代码地址

github.com/anyeyongzho…

1.安装

npm i marked @types/marked

2.使用

主要步骤:

(1). 导入md文件

(2). 使用marked转化

(3). 使用v-html展示在页面上

...
<div class="tip" v-html="markdownContent"></div>
...

import { marked } from 'marked';

onMounted(async () => {
  const mdFileContent = await import('./code.md?raw');
  markdownContent.value = marked(mdFileContent.default);
});

image.png

3.结合hightlight.js使用

(1)安装

npm i highlight.js

(2)写成指令

1)编写/views/directive/markedDirective.ts

import hljs from 'highlight.js';
import { marked } from 'marked';
import { Directive, DirectiveHook, nextTick, App, DirectiveBinding } from 'vue';

const render = new marked.Renderer();
marked.setOptions({
  renderer: render,
  gfm: true,
  pedantic: false,
});

const formatValue: DirectiveHook = async (el, binding) => {
  const html = marked(binding?.value ?? '');

  el.innerHTML = html;
  await nextTick();

  if (binding.arg === 'hl') {
    const blocks = el.querySelectorAll('pre code');
    blocks.forEach((block: any) => {
      hljs.highlightBlock(block);
    });
  }
};

const markedDirective: Directive = {
  mounted: formatValue,
  updated: formatValue,
};

export function setMarkedDirective(app: App) {
  app.directive('marked', markedDirective);
}

2)注册到/views/directive/index.ts

import type { App } from 'vue';
import { setMarkedDirective } from '/@/directive/markedDirective';

/**
 * 导出指令方法:v-xxx
 */
export function directive(app: App) {
  //markdown文件中代码高亮
  setMarkedDirective(app);
}

3)注册到main.ts

import { createApp } from 'vue'
import { directive } from '/@/directive/index'

const app = createApp(App)

directive(app)

app.mount('#app')

(3)组件中使用指令

...
<div class="tip" v-marked:hl="markdownContent"></div>
...

import { marked } from 'marked';
import 'highlight.js/styles/monokai-sublime.css';

const markdownContent = ref(null);
onMounted(async () => {
  const mdFileContent = await import('./code.md?raw');
  markdownContent.value = marked(mdFileContent.default);
});

这样markdowm文件中代码的部分就进行了高亮

image.png