之前渲染 Markdown 的時候, 筆者使用的是 mavonEditor 的預覽模式, 使用起來比較爽, 只需要引入組件即可, 但是在最近的開發中, 遇到了困難.
主要問題在于作為單頁面應用, 站內鏈接必須是使用 router-link 跳轉, 如果使用 mavonEditor 默認渲染的 a 標簽, 就會重新加載頁面, 用戶體驗較差.
動態渲染
想要實現在前端動態地根據用戶內容渲染router-link , 需要使用動態渲染, 根據 官方文檔, 直接修改vue.config.js 即可:
1
2
3
4
|
// vue.config.js module.exports = { runtimeCompiler: true } |
渲染 Markdown
筆者使用的是 markdown-it, 配置過程如下:
安裝
1
2
3
|
npm install markdown-it --save # 本體 npm install markdown-it-highlightjs --save # 代碼高亮 npm install markdown-it-katex --save # latex 支持 |
這里還另外安裝了兩個語法插件, 如果有其他需要的話, 可以在 npm 上搜索
靜態文件導入
highlight.js
通過 cdn 導入, 在 index.html 中加入:
1
2
|
< link rel = "stylesheet" href = "//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.5.0/build/styles/default.min.css" rel = "external nofollow" > < script src = "//cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.5.0/build/highlight.min.js" ></ script > |
github-markdown-css
markdown 的樣式
安裝
1
|
npm install github-markdown-css --save |
導入
在 main.js 文件中添加
1
|
import 'github-markdown-css/github-markdown.css' |
katex
通過 cdn 導入, 在 index.html
中加入:
1
|
< link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css" rel = "external nofollow" > |
使用
首先在 components
目錄下創建 Markdown.vue
文件,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<template> <components :is= "html" class= "markdown-body" ></components> </template> <script> import MarkdownIt from 'markdown-it' import hljs from 'markdown-it-highlightjs' import latex from 'markdown-it-katex' export default { name: 'Markdown' , props: { content: String }, data: () => ({ md: null }), computed: { // 使用 computed 才能在動態綁定時動態更新 html: function () { let res = this .md.render( this .content) // 使用正則表達式將站內鏈接替換為 router-link 標簽 res = res.replace(/<a href= "(?!http:\/\/|https:\/\/)(.*?)" rel= "external nofollow" >(.*?)<\/a>/g, '<router-link to="$1">$2</router-link>' ) // 使用正則表達式將站外鏈接在新窗口中打開 res = res.replace(/<a href= "(.*?)" rel= "external nofollow" >(.*?)<\/a>/g, '<a href="$1" rel="external nofollow" target="_blank">$2</a>' ) return { template: '<div>' + res + '</div>' } } }, created () { this .md = new MarkdownIt() this .md.use(hljs).use(latex) } } </script> |
然后在想使用的地方導入即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<template> <div> <Markdown :content= "content" /> </div> </template> <script> import Markdown from '@/components/Markdown.vue' export default { name: 'Home' , components: { Markdown }, data: () => ({ content: '' }), created () { this .content = '# 測試' } } </script> |
以上就是Vue單頁面應用中實現Markdown渲染的詳細內容,更多關于vue Markdown渲染的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/youxam/p/vue-markdown-render.html