Vue集成markdown

第一步

安装mavon-editor

npm install mavon-editor --save

第二步

在main.js注册mavon-editor并使用

// 全局注册
    // import with ES6
    import Vue from 'vue'
    import mavonEditor from 'mavon-editor'
    import 'mavon-editor/dist/css/index.css'
    // use
    Vue.use(mavonEditor)
    new Vue({
        'el': '#main',
        data() {
            return { value: '' }
        }
    })

第三步

创建、组件用于编辑

<template>
    <div>
      
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" >
        
          <el-form-item label="博客标题" prop="title">
            <el-input v-model="ruleForm.title" autocomplete="off">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 
                    ref="md" 
                    v-model="ruleForm.content" 
                    placeholder="请编辑文章内容"
                    :ishljs="true" 
                    @imgAdd="imgAdd"
            />
   
          el-form-item>

          <el-form-item>
          <el-button type="danger" @click="resetForm('ruleForm')" icon="el-icon-warning">重 置el-button>
          <el-button type="primary" @click="submitForm('ruleForm')" icon="el-icon-s-promotion">发 布el-button>
        el-form-item>
        
      
      el-form>
    div>
  template>

js代码

<script>
  export default {
    name: "editBlog",
    data() {
      return {
        ruleForm: {
          userId: '',
          title: '',
          description: '',
          content: ''
        },
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 3, max: 25, message: '长度在 3 到 25 个字符', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '请输入摘要', trigger: 'blur' }
          ],
          content: [
            { trequired: true, message: '请输入内容', trigger: 'blur' }
          ]
        },
        user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      };
    },

    //编辑渲染页面信息
    created() {
      const blogId = this.$route.params.blogId
      if(blogId) {
          this.request.get(`/blog/details/${blogId}`).then(res => {
          const blog = res.data
          this.ruleForm.id = blog.id
          this.ruleForm.title = blog.title
          this.ruleForm.description = blog.description
          this.ruleForm.content = blog.content
        })
      }
    },
    methods: {
      // 绑定@imgAdd event
      $imgAdd(pos, $file) {
        // console.log(pos,$file);
        let $vm = this.$refs.md
      // 第一步.将图片上传到服务器.
      const formdata = new FormData();
      formdata.append('image', $file);
      // this.$axios.post(`${this.api}/file/upload`,{
        this.request.post(`/file/upload`,{
          data:formdata,
          headers: {'Content-Type': 'multipart/form-data'}
        }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        // console.log(res);
        $vm.$img2Url(pos, res.data.data);
      })
    },

      //发布博客
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            if (!this.$cookies.get('access_token')) {
              this.$message.error('还没登录,请先登录!!!')
              return
            }

            this.ruleForm.userId = this.user.id
            this.request.post(`/blog/edit`, this.ruleForm).then(res => {
              if(res.code === 200){
                this.$message.success(res.msg)
                this.$router.push("/blogList")
              }
            })
          } else {
            // console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
  </script>

第四步

创建组件用于浏览文章的内容

<template>
    <div> 
	
        <mavon-editor
          class="md"
          :value="blog.content"
          :subfield="false"
          :defaultOpen="'preview'"
          :toolbarsFlag="false"
          :editable="false"
          :scrollStyle="true"
          :ishljs="true"
      />
    div>
template>

js代码

<script>  
    export default {
      name: "blogDetail",
      data() {
        return {
		blog: {
            		userId: 0,
            		id:0,
            		title: "",
            		description: '',
            		content: ""
          		},
		id: this.$route.params.blogId,
		},

      created() {      
        const blogId = this.$route.params.blogId
          this.request.get(`/blog/details/${blogId}`).then(res => {
            if(res.code === 200){
              this.blog = res.data
            }
        }),
        this.loadComment()
      },
  </script>

至此vue集成markdown就完毕了。

API 文档

props

name 名称 type 类型 default 默认值 describe 描述
value String 初始值
language String zh-CN 语言选择,暂支持 zh-CN: 简体中文, zh-TW: 正体中文 , en: 英文 , fr: 法语, pt-BR: 葡萄牙语, ru: 俄语, de: 德语, ja: 日语
fontSize String 14px 编辑区域文字大小
scrollStyle Boolean true 开启滚动条样式(暂时仅支持chrome)
boxShadow Boolean true 开启边框阴影
boxShadowStyle String 0 2px 12px 0 rgba(0, 0, 0, 0.1) 边框阴影样式
transition Boolean true 是否开启过渡动画
toolbarsBackground String #ffffff 工具栏背景颜色
previewBackground String #fbfbfb 预览框背景颜色
subfield Boolean true true: 双栏(编辑预览同屏), false: 单栏(编辑预览分屏)
defaultOpen String 在单栏(subfield=false)时默认展示区域. edit: 默认展示编辑区域, preview: 默认展示预览区域 其他 = edit
placeholder String 开始编辑… 输入框为空时默认提示文本
editable Boolean true 是否允许编辑
codeStyle String code-github markdown样式: 默认github, 可选配色方案
toolbarsFlag Boolean true 工具栏是否显示
navigation Boolean false 默认展示目录
shortCut Boolean true 是否启用快捷键
autofocus Boolean true 自动聚焦到文本框
ishljs Boolean true 代码高亮
imageFilter function null 图片过滤函数,参数为一个File Object,要求返回一个Boolean, true表示文件合法,false表示文件不合法
imageClick function null 图片点击事件,默认为预览,可覆盖
tabSize Number \t tab转化为几个空格,默认为\t
html Boolean true 启用HTML标签,因为历史原因这个标记一直默认为true,但建议不使用HTML标签就关闭它,它能彻底杜绝安全问题。
xssOptions Object {} xss规则配置, 默认开启,设置false可以关闭,开启后会对HTML标签进行过滤,默认过滤所有HTML标签属性,建议按需配置白名单减少被攻击的可能。 - 自定义规则参考: https://jsxss.com/zh/options.html - 参考DEMO: dev-demo
toolbars Object 如下例 工具栏

toolbars

默认工具栏按钮全部开启, 传入自定义对象,可以选择启用部分按钮

/*
  例如: {
      bold: true, // 粗体
      italic: true,// 斜体
      header: true,// 标题
  }
  此时, 仅仅显示此三个功能键
*/
toolbars: {
    bold: true, // 粗体
    italic: true, // 斜体
    header: true, // 标题
    underline: true, // 下划线
    strikethrough: true, // 中划线
    mark: true, // 标记
    superscript: true, // 上角标
    subscript: true, // 下角标
    quote: true, // 引用
    ol: true, // 有序列表
    ul: true, // 无序列表
    link: true, // 链接
    imagelink: true, // 图片链接
    code: true, // code
    table: true, // 表格
    fullscreen: true, // 全屏编辑
    readmodel: true, // 沉浸式阅读
    htmlcode: true, // 展示html源码
    help: true, // 帮助
    /* 1.3.5 */
    undo: true, // 上一步
    redo: true, // 下一步
    trash: true, // 清空
    save: true, // 保存(触发events中的save事件)
    /* 1.4.2 */
    navigation: true, // 导航目录
    /* 2.1.8 */
    alignleft: true, // 左对齐
    aligncenter: true, // 居中
    alignright: true, // 右对齐
    /* 2.2.1 */
    subfield: true, // 单双栏模式
    preview: true, // 预览
}

如果需要自定义添加工具栏按钮,可以通过以下方式

<mavon-editor>
  
  <template slot="left-toolbar-before">
    <button
      type="button"
      @click="$click('test')"
      class="op-icon fa fa-mavon-align-left"
      aria-hidden="true"
      title="自定义"
    >button>
  template>
  
  <template slot="left-toolbar-after">
    <button
      type="button"
      @click="$click('test')"
      class="op-icon fa fa-mavon-align-left"
      aria-hidden="true"
      title="自定义"
    >button>
  template>
  
  <template slot="right-toolbar-before">
    <button
      type="button"
      @click="$click('test')"
      class="op-icon fa fa-mavon-align-left"
      aria-hidden="true"
      title="自定义"
    >button>
  template>
  
  <template slot="right-toolbar-after">
    <button
      type="button"
      @click="$click('test')"
      class="op-icon fa fa-mavon-align-left"
      aria-hidden="true"
      title="自定义"
    >button>
  template>
mavon-editor>

events 事件绑定

name 方法名 params 参数 describe 描述
change String: value , String: render 编辑区发生变化的回调事件(render: value 经过markdown解析后的结果)
save String: value , String: render ctrl + s 的回调事件(保存按键,同样触发该回调)
fullScreen Boolean: status , String: value 切换全屏编辑的回调事件(boolean: 全屏开启状态)
readModel Boolean: status , String: value 切换沉浸式阅读的回调事件(boolean: 阅读开启状态)
htmlCode Boolean: status , String: value 查看html源码的回调事件(boolean: 源码开启状态)
subfieldToggle Boolean: status , String: value 切换单双栏编辑的回调事件(boolean: 双栏开启状态)
previewToggle Boolean: status , String: value 切换预览编辑的回调事件(boolean: 预览开启状态)
helpToggle Boolean: status , String: value 查看帮助的回调事件(boolean: 帮助开启状态)
navigationToggle Boolean: status , String: value 切换导航目录的回调事件(boolean: 导航开启状态)
imgAdd String: filename, File: imgfile 图片文件添加回调事件(filename: 写在md中的文件名, File: File Object)
imgDel String: filename 图片文件删除回调事件(filename: 写在md中的文件名)

代码高亮

如不需要hightlight代码高亮显示,你应该设置ishljs为false

开启代码高亮props


<mavon-editor :ishljs="true">mavon-editor>

为优化插件体积,从v2.4.2起以下文件将默认使用cdnjs外链:

  • highlight.js
  • github-markdown-css
  • katex(v2.4.7)

代码高亮highlight.js中的语言解析文件和代码高亮样式将在使用时按需加载. github-markdown-csskatex仅会在mounted时加载

Notice: 可选配色方案 和 支持的语言 是从 highlight.js/9.12.0 导出的

不使用cdn,本地按需加载点击这里…

图片上传

<template>
    <mavon-editor ref=md @imgAdd="$imgAdd" @imgDel="$imgDel">mavon-editor>
template>
<script>
export default {
    methods: {
        // 绑定@imgAdd event
        $imgAdd(pos, $file){
            // 第一步.将图片上传到服务器.
           var formdata = new FormData();
           formdata.append('image', $file);
           axios({
               url: 'server url',
               method: 'post',
               data: formdata,
               headers: { 'Content-Type': 'multipart/form-data' },
           }).then((url) => {
               // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
               /**
               * $vm 指为mavonEditor实例,可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后,`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `,`$vm`为 `this.$refs.md`
               */
               $vm.$img2Url(pos, url);
           })
        }
    }
}
script>

图片上传详情点击这里…

  • 默认大小样式为 min-height: 300px , min-width: 300px 可自行覆盖
  • 基础z-index: 1500
  • 仅用作展示可以设置props: toolbarsFlag: false , subfield: false, defaultOpen: “preview”

快捷键

key keycode 功能
F8 119 开启/关闭导航
F9 120 预览/编辑切换
F10 121 开启/关闭全屏
F11 122 开启/关闭阅读模式
F12 123 单栏/双栏切换
TAB 9 缩进
CTRL + S 17 + 83 触发保存
CTRL + D 17 + 68 删除选中行
CTRL + Z 17 + 90 上一步
CTRL + Y 17 + 89 下一步
CTRL + BreakSpace 17 + 8 清空编辑
CTRL + B 17 + 66 加粗
CTRL + I 17 + 73 斜体
CTRL + H 17 + 72 # 标题
CTRL + 1 17 + 97 or 49 # 标题
CTRL + 2 17 + 98 or 50 ## 标题
CTRL + 3 17 + 99 or 51 ### 标题
CTRL + 4 17 + 100 or 52 #### 标题
CTRL + 5 17 + 101 or 53 ##### 标题
CTRL + 6 17 + 102 or 54 ###### 标题
CTRL + U 17 + 85 ++下划线++
CTRL + M 17 + 77 标记
CTRL + Q 17 + 81 > 引用
CTRL + O 17 + 79 1. 有序列表
CTRL + L 17 + 76 链接标题
CTRL + ALT + S 17 + 18 + 83 上角标
CTRL + ALT + U 17 + 18 + 85 - 无序列表
CTRL + ALT + C 17 + 18 + 67 ```代码块
CTRL + ALT + L 17 + 18 + 76 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-khW3bQUw-1663079268459)(图片链接)]
CTRL + ALT + T 17 + 18 + 84 表格
CTRL + SHIFT + S 17 + 16 + 83 下角标
CTRL + SHIFT + D 17 + 16 + 68 中划线
CTRL + SHIFT + C 17 + 16 + 67 居中
CTRL + SHIFT + L 17 + 16 + 76 居左
CTRL + SHIFT + R 17 + 16 + 82 居右
SHIFT + TAB 16 + 9 取消缩进

你可能感兴趣的:(vue.js,javascript,前端)