Vue 中引入markdown富文本编辑器

在vue组件中,比较好用的是mavon-editor,github文档地址 https://github.com/hinesboy/mavonEditor

  1. 安装

npm install mavon-editor --save

  1. 在 main.js 中注册该组件
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

// use
Vue.use(mavonEditor)
  1. 在组件中使用
<!-- 表单的内容使用markdown富文本编辑器 -->
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
  <el-form-item label="标题" prop="title">
    <el-input v-model="ruleForm.title"></el-input>
  </el-form-item>

  <el-form-item label="摘要" prop="description">
    <el-input type="textarea" v-model="ruleForm.description"></el-input>
  </el-form-item>

  <el-form-item label="内容" prop="content">
    <mavon-editor class="mk-editor" v-model="ruleForm.content"></mavon-editor>
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">立即发布</el-button>
    <el-button @click="resetForm('ruleForm')">重置</el-button>
  </el-form-item>
</el-form>
  1. 后端传过来的内容如果是 markdown 格式的内容,需要进行渲染然后显示出来,这里我们可以使用一个插件 markdown-it,用于解析 md 文档,然后导入 github-markdown-c,所谓 md 的样式。
  2. 安装命令
# 用于解析 markdown 格式的文档:
npm install markdown-it --save
# markdown 样式
npm install github-markdown-css
  1. 接下来就可以在需要渲染的地方使用
<template>
	<div class="markdown-body" v-html="xxx.content"></div>
</template>

<script>
import 'github-markdown-css'
    
export default {
  name: "xx",
  components: {Header},
  data() {
    return {
      xxx: {
        id: "",
        title: "",
        content: ""
      }
    }
  },
  created() {
      
    var MardownIt = require("markdown-it")
	var md = new MardownIt()

	var result = md.render(xxx.content)
  }
</script>
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐