在Vue 中使用 Vditor
官方文档 Vditor
- 安装
npm install vditor --save
- 引入
import Vditor from ‘vditor’
import ‘vditor/dist/index.css’
- 使用
new Vue({
el: '#app',
data: {
contentEditor: '',//组件实例
},
mounted () {
this.contentEditor = new Vditor('vditor', {
height: 360, //设置高度
toolbarConfig: {
pin: true,
},
cache: {
enable: false,
},
after: () => {
//渲染完成 触发方法
this.contentEditor.setValue('hello, Vditor + Vue!')
},
})
},
})
markdown编辑分为3种模式
options中mode字段可选值
- sv (分屏预览)
- ir (即时渲染)
- wysiwyg (所见即所得)
完整示例
<template>
<div class="plugin-markdown">
<div class="plugin-markdown-header">
<span class="edit">编辑</span>
<span class="prevew">预览</span>
</div>
<div
id="vditor"
name="description"
></div>
</div>
</template>
<script>
import Vditor from 'vditor'
import 'vditor/dist/index.css'
export default {
name: 'MarkDown',
props: {
actionItem: {
type: Object,
default: () => {}
}
},
data() {
return {
contentEditor: {}
}
},
mounted() {
this.contentEditor = new Vditor('vditor', {
height: 360,
cache: {
enable: false
},
value: this.actionItem.pluginAction.message,
mode: 'sv',
preview: {
mode: 'both'
},
after: () => {
// 渲染完成后触发 回显用
if (this.actionItem.pluginAction.message) {
this.contentEditor.setValue(this.actionItem.pluginAction.message)
}
},
input: () => {
//输入时触发
if (this.contentEditor.getHTML()) {
this.actionItem.pluginAction.message = this.contentEditor.getValue()
} else {
this.actionItem.pluginAction.message = ''
}
}
})
}
}
</script>
<style lang="scss">
.plugin-markdown {
width: 100%;
em {
font-style: italic;
}
ol {
list-style-type: decimal;
}
a {
outline: 0;
text-decoration: none;
color: #4285f4;
}
&-header {
width: 100%;
display: flex;
border: 1px solid #d1d5da;
border-bottom: unset;
.edit,
.prevew {
display: inline-block;
padding: 10px 0px 10px 16px;
border-right: 1px solid #d1d5da;
font-size: 16px;
color: #272e3b;
}
.edit {
width: 545.91px;
}
.prevew {
flex: 1;
border-right: 0;
}
}
.vditor-preview__action {
display: none;
}
}
</style>