vue2.6.11 中使用wangeditor5

安 装

npm install @wangeditor/editor --save
npm install @wangeditor/editor-for-vue --save

导入

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
    name: 'MarkDown',
    components: {
      Editor,
      Toolbar
    },

使用

 
{{blogForm.title.trim().length}}/50

配置

  data () {
      return {
        editor: null,
        toolbarConfig: {
          excludeKeys: ['fullScreen']
        },
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            uploadImage:{
              maxNumberOfFiles: 1,
              customUpload: this.editorUpload
            },
            uploadVideo:{
              maxNumberOfFiles: 1,
              customUpload: this.editorUpload
            },
          }

        }
       }

自定义图片和视频上传

  // 编辑器上传图片视频
     async editorUpload(file,insertFn){
        let formData = new FormData()
        if (file.size > 5 * 1024 * 1024) {
          return this.$message.warning('上传的图片或视频大小不超过5M')
        }
        formData.append('file', file)
        const { data: res } = await uploadFile(formData)
        if (res.code === 0) {
          this.$message.success("上传成功")
          insertFn(res.imgUrl)
        }
      },
      //上传图片
      async uploadImg (e, index) {
        let files = e.target.files
        let formData = new FormData()
        if (files[0].size > 5 * 1024 * 1024) {
          return this.$message.warning('上传的图片大小不超过5M')
        }
        formData.append('file', files[0])
        const { data: res } = await uploadFile(formData)
        if (res.code === 0) {
          this.$message.success('图片上传成功')
          if (index) {
            this.blogForm.firstPicture = res.imgUrl
          }
        } else {
          this.$message.error('图片上传失败')
        }

      },

自定义代码高亮、行号、复制 指令

import Hljs from 'highlight.js'
import { lineNumbersBlock } from '../utils/highlight-line-number'
import { onCopy, htmlDecode } from '../utils/copy'
const hljsTheme = localStorage.getItem('HLJS_THEME') || 'atom-one-dark.css'//缓存的变量
import(`highlight.js/styles/${hljsTheme}`)
let count = 0
let Highlight = {}
Highlight.install = (Vue, options) => {
  Vue.directive('highlight', (el, val) => {
    let blocks
    if (val.value.id < 54) {
      blocks = el.querySelectorAll('pre')
    } else {
      blocks = el.querySelectorAll('pre code')
    }
    if (count === 0) {
      blocks.forEach((block) => {
        let code = block.innerHTML

        Hljs.highlightElement(block)
        if (val.value.flag) {
          lineNumbersBlock(block,{singleLine:true})
          if (val.value.id >= 54) {
            handlerCopy(block, code)
          }
        }
      })
      handlerImgPre(el)
    }
    if (val.value.id) {
      count++
    }

  })
}

function handlerCopy (block, code) {
  block.innerHTML = `${block.innerHTML}`
  let copyButton = block.querySelector('button')
  if (copyButton != null) {
    copyButton.onclick = function () {
      onCopy(htmlDecode(code))
      console.log('复制成功')
    }
  }
}
function handlerImgPre (el) {
   let imgs = el.querySelectorAll("img")
  imgs.forEach(item=>{
    item.style.cursor="zoom-in"
    let src=item.src
    item.onclick=()=>{
       let div = document.createElement("div")
      let image = new Image()
      image.src=src
      div.className="plus-image"
      div.appendChild(image)
      div.onclick=()=>{
         div.remove()
      }
      document.body.appendChild(div)
    }
  })
}
export default Highlight

工具类(copy.js)

import { Message } from 'element-ui'

export function onCopy (code) {
  let oInput = document.createElement('textarea')
  oInput.value = code
  document.body.appendChild(oInput)
  oInput.select() // 选择对象;
  document.execCommand('Copy') // 执行浏览器复制命令
  Message.success('复制成功')
  oInput.remove()
}

export function htmlDecodeByRegExp (str) {
  let temp = ''
  if (str.length === 0) return ''
  temp = str.replace(/&/g, '&')
  temp = temp.replace(//g, '>')
  temp = temp.replace(/ /g, ' ')
  temp = temp.replace(/'/g, '\'')
  temp = temp.replace(/"/g, '"')
  return temp
}

export function htmlDecode (text) {
  //1.首先动态创建一个容器标签元素,如DIV
  var temp = document.createElement('div')
  //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
  temp.innerHTML = text
  //3.最后返回这个元素的innerText或者textContent,即得到经过HTML解码的字符串了。
  var output = temp.innerText || temp.textContent
  temp = null
  return output
}

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