Vue項目中引用富文本編輯器-TinyMCE


前言:

遇到需求,需要在vue項目中引入富文本編輯器,對比了幾種編輯器,最終選擇了tinymce,基本效果圖如下:

TinyMCE的中文文檔地址:http://tinymce.ax-z.cn/

安裝:

1、下載依賴包

npm i @tinymce/tinymce-vue -S
npm i tinymce -S

2、下載完成后,在vue項目存放靜態資源的文件夾中新建一個文件夾tinymce,到node_modules中找到tinymce/skins目錄,將skins文件夾拷貝到新建的tinymce文件夾中

3、中文化:語言包地址,下載語言包,解壓將langs文件夾拷貝到vue項目靜態資源路徑下的tinymce文件夾中

具體如下圖:

使用:

將tinymce封裝成組件,完整代碼如下:

<template>
  <div class="tinymce-box">
    <editor v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick"> </editor>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce' //tinymce默認hidden,不引入不顯示
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/icons/default/icons'
import 'tinymce/themes/silver'
// 編輯器插件plugins
// 更多插件參考:https://www.tiny.cloud/docs/plugins/
import 'tinymce/plugins/image' // 插入上傳圖片插件
import 'tinymce/plugins/media' // 插入視頻插件
import 'tinymce/plugins/table' // 插入表格插件
import 'tinymce/plugins/lists' // 列表插件
import 'tinymce/plugins/wordcount' // 字數統計插件
export default {
  components: {
    Editor
  },
  name: 'tinymce',
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default: 'lists image media table wordcount'
    },
    toolbar: {
      type: [String, Array],
      default:
        'undo redo |  formatselect | fontsizeselect  fontselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image table | removeformat'
    }
  },
  data() {
    return {
      init: {
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide',
        // skin_url: 'tinymce/skins/ui/oxide-dark',//暗色系
        font_formats: '微軟雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;蘋果蘋方=PingFang SC,Microsoft YaHei,sans-serif;宋體=simsun,serif',
        fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px',
        height: 300,
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: false,
        menubar: false,
        convert_urls: false,
        // images_upload_base_path: process.env.BASE_URL + '/test/',
        // relative_urls : false,
        // remove_script_host : true,
        // document_base_url: location.protocol + '//' + location.hostname,
        // 此處為圖片上傳處理函數,這個直接用了base64的圖片形式上傳圖片,
        // 如需ajax上傳可參考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, success, failure) => {
          const img = 'data:image/jpeg;base64,' + blobInfo.base64()
          success(img)
        },
        urlconverter_callback: function(url, node, on_save, name) {
          return url
        },
        setup: editor => {
          editor.on('blur', () => {
            this.$emit('onBlur', this.myValue)
          })
        }
      },
      myValue: this.value
    }
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    // 添加相關的事件,可用的事件參照文檔=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    },
    // 可以添加一些自己的自定義事件,如清空內容
    clear() {
      this.myValue = ''
    },
    getWordcount() {
      return tinymce.activeEditor.plugins.wordcount
    },
    // 自定義方法,判斷編輯器內是否有有效內容
    isNoEmpty() {     
      let wordcount = this.getWordcount()
      const reg1 = /<table.*?>[\s\S]*<\/table>/
      const reg2 = /<ul.*?>[\s\S]*<\/ul>/
      const reg3 = /<ol.*?>[\s\S]*<\/ol>/
      const reg4 = /<img.*?>/
      let count = wordcount.body.getWordCount()

      return reg1.test(this.myValue) || reg2.test(this.myValue) || reg3.test(this.myValue) || reg4.test(this.myValue) || count > 0
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    }
  }
}
</script>
<style scoped></style>

使用封裝組件:

<tinymce ref="editor" :key="tinymceFlag" v-model="goodsDescp" />

關於init屬性的解釋:

1、font_formats:字體格式
2、
fontsize_formats:字體大小
3、convert_urls

過程中踩過的坑及解決方法:

1、在keep-alive中使用自定義封裝組件時,第一次進入頁面編輯器能正常使用,切換頁面再次進入時編輯器無法正常使用,解決方法是給組件加動態key值,打破dom復用,參考代碼如下:

activated() {
    this.tinymceFlag++
}

2、圖片上傳默認是以base64的圖片形式上傳圖片,也可以實現通過請求方式將圖片上傳到服務器中並返回圖片地址,在images_upload_handler配置中實現,參考代碼如下:

images_upload_handler: (blobInfo, success, failure) => {
  // const img = 'data:image/jpeg;base64,' + blobInfo.base64()
  // success(img)
  var xhr, formData

  xhr = new XMLHttpRequest()
  xhr.withCredentials = false
  xhr.open('POST', '...') // 省略請求地址

  xhr.onload = function() {
// 可自定義返回數據格式,根據自己需求進行處理 var json if (xhr.status != 200) { failure('HTTP Error: ' + xhr.status) return } json = JSON.parse(xhr.responseText) if (!json || !json.success) { failure((json ? '' : 'Invalid JSON: ') + xhr.responseText) return } success(json.data.url) } formData = new FormData() formData.append('file', blobInfo.blob(), blobInfo.filename()) xhr.send(formData) }

3、如果圖片上傳服務器返回的是相對地址,在編輯器中需要使用絕對地址,可通過urlconverter_callback配置格式化url,參考代碼如下:

urlconverter_callback: function(url, node, on_save, name) {
  if (url.indexOf('http://') !== -1) {
    return url
  }
  url = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + url
  // Return new URL
  return url
}

4、自定義圖標功能,可在setup配置中實現

5、校驗編輯器內容必填,測試要求考慮編輯器內容只有`回車,空字符`時也算無內容,處理思路是,通過編輯器的字數統計插件來獲取當前編輯器內字數,作為判斷條件

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM