1. 本次我們使用到的Markdown插件為mavonEditor, 好!開始:
安裝所需插件:
yarn add mavon-editor
OR
npm install mavon-editor -S
2. 在main.js中引入並使用:
import mavonEditor from 'mavon-editor' import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor)
這里的css是不能少的(如果你想自己寫樣式話就沒事了)。
如果還是沒有樣式,可以在public下的index.html文件中添加
<link href="https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css" rel="stylesheet">
3. 在vue組件中使用:
<mavon-editor :value="value" @change="valueChange" />
這里綁定的change函數會在編輯輸入時觸發傳回的params: { value: 你輸入的文本, render: markdown編譯之后返回的HTML文本 }
<script> export default { name: "MarkDown", data() { return { value: "# ddd", }; }, methods: { valueChange(value, render) { //value為輸入的內容,render是markdown渲染之后的html代碼 console.log(value, render); }, }, } </script>
效果圖:
4. 指定頁面展示編寫的MD內容:
我們只需在頁面組件中添加容器標簽並使用v-html插入即可:
<div v-html="htmlText" class="markdown-body" />
這里的htmlText就是markdown編譯之后返回的html文本內容,上方函數觸發時記得保存render的值,class就是之前說的樣式辣,但是注意自己是否有樣式影響這里的布局,如果文本自己居中了,可以嘗試在此處添加css:text-align: left。
效果:
5. 可能在使用v-html時會出現XSS警告,可以使用插件vue-dompurify-html:
安裝:
yarn add vue-dompurify-html OR npm i vue-dompurify-html -S
在main.js中引入使用
import VueDOMPurifyHTML from 'vue-dompurify-html' Vue.use(VueDOMPurifyHTML)
將 v-html 替換為 v-dompurify-html 。 搞定!!