在Vue中使用Vditor編輯器
1.技術概述
Vditor 是一款瀏覽器端的 Markdown 編輯器,支持所見即所得、即時渲染(類似 Typora)和分屏預覽模式。它使用TypeScript實現,支持原生JavaScript、Vue、React、Angular,提供桌面版。
2.技術詳述
1.首先安裝vditor
npm install vditor --save
用VScode直接在終端輸入,如下圖
2.檢查package.json中是否存在vidor依賴,如果有則引入成功,如果沒有可能是網絡原因導致可以試試多次嘗試步驟1。

3.使用
使用方法如下:
import Vditor from "vditor";
import "vditor/src/assets/scss/index.scss";
this.contentEditor = new Vditor('vditor', {
...})
div id = "vditor"
<template>
<div id="vditor" name="description" ></div>
</template>
<script>
import Vditor from "vditor";
import "vditor/src/assets/scss/index.scss";
export default {
data(){
return{
contentEditor: {},
}
},
mounted(){
this.contentEditor = new Vditor('vditor', {
height: 500,
placeholder: '此處為話題內容……',
theme: 'classic',
counter: {
enable: true,
type: 'markdown'
},
preview: {
delay: 0,
hljs: {
style: 'monokai',
lineNumber: true
}
},
tab: '\t',
typewriterMode: true,
toolbarConfig: {
pin: true
},
cache: {
enable: false
},
mode: 'sv',
toolbar: [
'emoji',
'headings',
'bold',
'italic',
'strike',
'link',
'|',
'list',
'ordered-list',
'check',
'outdent',
'indent',
'|',
'quote',
'line',
'code',
'inline-code',
'insert-before',
'insert-after',
'|',
// 'record',
'table',
'|',
'undo',
'redo',
'|',
'edit-mode',
// 'content-theme',
'code-theme',
'export',
{
name: 'more',
toolbar: [
'fullscreen',
'both',
'preview',
'info',
'help',
],
}],
})
}
}
</script>
步驟詳解:
1.使用import引入
import Vditor from 'vditor'
import 'vditor/dist/index.css'

2.創建一個Vditor實例並賦值給contentEditor
其中new Vditor('vditor',{...})中的第一個參數vditor將Vditor編輯器關聯到id為vditor的標簽。
這里contentEditor被賦值為Vditor實例,后續可以通過this.contentEditor.方法名(參數)來調用Vditor中的一些方法。


3.在前端代碼中使用
<div id="vditor"></div>

4.通過getValue()獲取輸入框內容
this.contentEditor.getValue()可以獲取輸入內容,提交表單方法中有多次使用到,如下所示:
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
if (
this.contentEditor.getValue().length === 1 ||
this.contentEditor.getValue() == null ||
this.contentEditor.getValue() === ''
) {
alert('話題內容不可為空')
return false
}
this.ruleForm.content = this.contentEditor.getValue()
......
})
},
3.技術使用中遇到的問題和解決過程
上面的使用部分使用Vditor時我們不難發現:前端與后端傳輸使用的是未經"翻譯"的markdown內容(如:##標題),如果我們將從后端獲取的內容不加處理地拿來顯示,‘##標題’還是會原樣顯示為‘##標題’,所以我們將其轉化為markdown形式。
方法如下所示:
1.renderMarkdown()方法中調用Vditor.preview()來進行轉換,第一個參數document.getElementById("preview")指的是id為preview的標簽,這里會將第二個參數md的內容轉化為markdown格式顯示在第一個參數所指標簽中。
renderMarkdown(md) {
Vditor.preview(document.getElementById("preview"), md, {
hljs: { style: "github" },
});
},
2.使用renderMarkdown()方法並傳入需要以markdown顯示的內容,這樣被傳入內容就會被修改為markdown形式。
this.renderMarkdown(this.blog.content);


4.總結
1.首先安裝vditor
npm install vditor --save
2.檢查package.json中是否存在vidor依賴
3.使用
-
引入
import Vditor from 'vditor'
import 'vditor/dist/index.css' -
創建一個Vditor實例並賦值給contentEditor
-
在前端代碼中使用
4.通過getValue()可以獲取輸入框內容
5.需要以markdown形式顯示