Vue單頁面應(yīng)用中實(shí)現(xiàn)Markdown渲染
之前渲染 Markdown 的時(shí)候, 筆者使用的是 mavonEditor 的預(yù)覽模式, 使用起來比較爽, 只需要引入組件即可, 但是在最近的開發(fā)中, 遇到了困難.
主要問題在于作為單頁面應(yīng)用, 站內(nèi)鏈接必須是使用 router-link 跳轉(zhuǎn), 如果使用 mavonEditor 默認(rèn)渲染的 a 標(biāo)簽, 就會(huì)重新加載頁面, 用戶體驗(yàn)較差.
動(dòng)態(tài)渲染想要實(shí)現(xiàn)在前端動(dòng)態(tài)地根據(jù)用戶內(nèi)容渲染router-link , 需要使用動(dòng)態(tài)渲染, 根據(jù) 官方文檔, 直接修改vue.config.js 即可:
// vue.config.jsmodule.exports = { runtimeCompiler: true}渲染 Markdown
筆者使用的是 markdown-it, 配置過程如下:
安裝npm install markdown-it --save # 本體npm install markdown-it-highlightjs --save # 代碼高亮npm install markdown-it-katex --save # latex 支持
這里還另外安裝了兩個(gè)語法插件, 如果有其他需要的話, 可以在 npm 上搜索
靜態(tài)文件導(dǎo)入highlight.js通過 cdn 導(dǎo)入, 在 index.html 中加入:
<link rel='stylesheet' rel='external nofollow' ><script src='http://www.piao2010.com/uploads/202102/21/16138832431.js'></script>github-markdown-css
markdown 的樣式
安裝npm install github-markdown-css --save導(dǎo)入
在 main.js 文件中添加
import ’github-markdown-css/github-markdown.css’katex
通過 cdn 導(dǎo)入, 在 index.html 中加入:
<link rel='stylesheet' rel='external nofollow' >使用
首先在 components 目錄下創(chuàng)建 Markdown.vue 文件,
<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 才能在動(dòng)態(tài)綁定時(shí)動(dòng)態(tài)更新 html: function () { let res = this.md.render(this.content) // 使用正則表達(dá)式將站內(nèi)鏈接替換為 router-link 標(biāo)簽 res = res.replace(/<a href='http://www.piao2010.com/bcjs/(?!http://|https://)(.*?)' rel='external nofollow' >(.*?)</a>/g, ’<router-link to='$1'>$2</router-link>’) // 使用正則表達(dá)式將站外鏈接在新窗口中打開 res = res.replace(/<a href='http://www.piao2010.com/bcjs/(.*?)' rel='external nofollow' >(.*?)</a>/g, ’<a href='http://www.piao2010.com/bcjs/$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>
然后在想使用的地方導(dǎo)入即可
<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單頁面應(yīng)用中實(shí)現(xiàn)Markdown渲染的詳細(xì)內(nèi)容,更多關(guān)于vue Markdown渲染的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP中實(shí)現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)2. vue前端RSA加密java后端解密的方法實(shí)現(xiàn)3. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)4. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能5. vue項(xiàng)目登錄成功拿到令牌跳轉(zhuǎn)失敗401無登錄信息的解決6. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)7. asp批量添加修改刪除操作示例代碼8. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享9. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享10. 淺談?dòng)蓀osition屬性引申的css進(jìn)階討論

網(wǎng)公網(wǎng)安備