如何在vue项目中使用markdown编辑器

在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>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值