切換語言為:簡體

Vue中使用富文字外掛Tinymce

  • 爱糖宝
  • 2024-10-23
  • 2057
  • 0
  • 0

一:vue2.X版本 安裝

@tinymce/tinymce-vue

  1. 網上查詢安裝版本

 npm install tinymce@5.1.0 -S
 
 npm install @tinymce/tinymce-vue@3.0.1 -S
  1. 本人專案中使用版本

"@tinymce/tinymce-vue": "^3.0.1",
"tinymce": "^5.10.2",

二:如何使用

  1. 把node_modules/tinymce下的skins 資料夾複製到public資料夾下

  2. 下載當地語言包 Language Packages | Trusted Rich Text Editor | TinyMCE 把解壓後的語言包xxx.js複製到public資料夾下

Vue中使用富文字外掛Tinymce

  1. 在src/views/或者src/componets/你自己的相關資料夾內建立一個vue檔案

Vue中使用富文字外掛Tinymce

  1. 檔案內容 次檔案內容可以直接複製使用

<template>
	<div class="tinymce">
		<editor id="tinymce" v-model="Html" :init="tinymceInit" @input="echoEditor" />
		<!-- <div v-html="Html"></div> -->
	</div>
</template>

<script>
import uploadApi from "@/api/uploadApi/upload"
import tinymce from "tinymce/tinymce"
import "tinymce/themes/silver/theme"
import Editor from "@tinymce/tinymce-vue"
import "tinymce/icons/default/icons"
import "tinymce/plugins/image"
import "tinymce/plugins/link"
import "tinymce/plugins/code"
import "tinymce/plugins/table"
import "tinymce/plugins/lists"
import "tinymce/plugins/contextmenu"
import "tinymce/plugins/wordcount"
import "tinymce/plugins/colorpicker"
import "tinymce/plugins/textcolor"
import "tinymce/plugins/print"
import "tinymce/plugins/preview"
import "tinymce/plugins/searchreplace"
import "tinymce/plugins/autolink"
import "tinymce/plugins/directionality"
import "tinymce/plugins/visualblocks"
import "tinymce/plugins/visualchars"
import "tinymce/plugins/media"
import "tinymce/plugins/fullscreen"
import "tinymce/plugins/template"
import "tinymce/plugins/codesample"
import "tinymce/plugins/charmap"
import "tinymce/plugins/hr"
import "tinymce/plugins/pagebreak"
import "tinymce/plugins/nonbreaking"
import "tinymce/plugins/anchor"
import "tinymce/plugins/insertdatetime"
import "tinymce/plugins/advlist"
import "tinymce/plugins/lists"
import "tinymce/plugins/wordcount"
import "tinymce/plugins/imagetools"
import "tinymce/plugins/textpattern"
import "tinymce/plugins/help"
import "tinymce/plugins/emoticons"
import "tinymce/plugins/autosave"
import "tinymce/plugins/autoresize"
// import 'tinymce/baseURL/icons/custom'
// import '../../../public/tinymce/plugins/emoticons'
import "../../../public/tinymce/plugins/bdmap/plugin"
import "../../../public/tinymce/plugins/indent2em/plugin"
import "../../../public/tinymce/plugins/axupimgs/plugin"
// import 'tinymce/plugins/formatpainter'
function suffix(file) {
  const fileNameOne = file.name.lastIndexOf(".") // 取到檔名開始到最後一個點的長度
  const fileNameLength = file.name.length // 取到檔名長度
  const fileFormat = file.name.substring(fileNameOne + 1, fileNameLength) // 截去後綴名
  return fileFormat
}
export default {
  name: "NewTinymce",

  components: { Editor },
  props: {
    tinymceHtml: {
      type: String,
      default: ""
    },
    contentDetails: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      Html: "",
      tinymceInit: {
        language_url: "../../../tinymce/zh_CN.js",
        language: "zh_CN",
        skin_url: "../../../tinymce/skins/ui/oxide",
        emoticons_database_url: "../../../tinymce/plugins/emoticons/js/emojis.js",
        plugins:
          "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave autoresize bdmap indent2em axupimgs",
        //     toolbar:
        //       'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
        // styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
        // table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight axupimgs',
        toolbar: [
          // eslint-disable-next-line no-multi-str
          "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
       styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
         table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight axupimgs"
        ],
        height: 650, // 編輯器高度
        min_height: 400,
        // icons: 'custom',
        // inline: true,
        // statusbar: false,
        content_css: "../../../tinymce/skins/content/default/content.css", // 可設定編輯區內容展示的css,謹慎使用
        /* '/static/reset.css',
        '/static/ax.css',
        '/static/css.css',
    ],*/
        fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
        font_formats:
          "微軟雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;蘋果蘋方=PingFang SC,Microsoft YaHei,sans-serif;宋體=simsun,serif;仿宋體=FangSong,serif;黑體=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
        link_list: [
          { title: "預置連結1", value: "http://www.tinymce.com" },
          { title: "預置連結2", value: "http://tinymce.ax-z.cn" }
        ],
        image_list: [
          { title: "預置圖片1", value: "https://www.tiny.cloud/images/glyph-tinymce@2x.png" },
          { title: "預置圖片2", value: "https://www.baidu.com/img/bd_logo1.png" }
        ],
        image_class_list: [
          { title: "None", value: "" }
          // { title: 'Some class', value: 'class-name' }
        ],
        importcss_append: true,
        // 自定義檔案選擇器的回撥內容
        file_picker_callback: function (callback, value, meta) {
          if (meta.filetype === "file") {
            // // 要先模擬出一個input用於上傳本地檔案
            var input = document.createElement("input")
            input.setAttribute("type", "file")
            // 你可以給input加accept屬性來限制上傳的檔案型別
            // 例如:input.setAttribute('accept', '.jpg,.png')
            input.setAttribute("accept", ".doc,.docx,.ppt,.pptx,.pdf,.xlsx")

            input.onchange = function () {
              var file = this.files[0]
              let suffixY = ""
              if (suffix(file) === "doc" || suffix(file) === "docx") {
                suffixY = "msword"
              } else if (suffix(file) === "pdf") {
                suffixY = "pdf"
              } else if (suffix(file) === "json") {
                suffixY = "json"
              }
              uploadApi.getUpload({ bucketName: "notice", objectName: file.name }).then(res => {
                uploadApi.uploadFile({ url: res.data.uploadPath, file: file }, "application/" + suffixY).then(data => {
                  callback(res.data.downloadPath, { text: file.name })
                })
              })
            }
            input.click()
            // callback('https://www.baidu.com/img/bd_logo1.png', { text: 'My text' })
          }
          if (meta.filetype === "image") {
            // callback('https://www.baidu.com/img/bd_logo1.png', { alt: 'My alt text' })
            // 要先模擬出一個input用於上傳本地檔案
            // var input = document.createElement("input")
            input.setAttribute("type", "file")
            // 你可以給input加accept屬性來限制上傳的檔案型別
            // 例如:input.setAttribute('accept', '.jpg,.png')
            input.setAttribute("accept", ".jpg,.png,.jpeg,.svg")
            input.onchange = function (e) {
              var file = this.files[0]
              let suffixY = ""
              if (suffix(file) === "png") {
                suffixY = "png"
              } else if (suffix(file) === "jpg") {
                suffixY = "jpeg"
              } else if (suffix(file) === "gif") {
                suffixY = "gif"
              }
              uploadApi.getUpload({ bucketName: "notice", objectName: file.name }).then(res => {
                uploadApi.uploadFile({ url: res.data.uploadPath, file: file }, "image/" + suffixY).then(data => {
                  callback(res.data.downloadPath, { text: file.name })
                })
              })
            }
            input.click()
          }
          if (meta.filetype === "media") {
            // callback('https://www.baidu.com/img/bd_logo1.png', { alt: 'My alt text' })
            // // 要先模擬出一個input用於上傳本地檔案
            // var input = document.createElement("input")
            input.setAttribute("type", "file")
            // 你可以給input加accept屬性來限制上傳的檔案型別
            // 例如:input.setAttribute('accept', '.jpg,.png')
            input.setAttribute("accept", ".mp4,.mov,.wmv,.flv")
            input.click()
            input.onchange = function () {
              var file = this.files[0]
              uploadApi.getUpload({ bucketName: "notice", objectName: file.name }).then(res => {
                uploadApi.uploadFile({ url: res.data.uploadPath, file: file }).then(data => {
                  callback(res.data.downloadPath, { text: file.name })
                })
              })
            }
            // callback('movie.mp4', { source2: 'alt.ogg', poster: 'https://www.baidu.com/img/bd_logo1.png' })
          }
        },
        // 多圖片上傳在富文字內展示的路徑(全路徑時為空)
        images_upload_base_path: "",
        images_upload_handler: function (blobInfo, succFun, failFun) {
          var file = blobInfo.blob() // 轉化為易於理解的file物件
          // // 要先模擬出一個input用於上傳本地檔案
          var input = document.createElement("input")
          input.setAttribute("type", "file")
          // 你可以給input加accept屬性來限制上傳的檔案型別
          // 例如:input.setAttribute('accept', '.jpg,.png')
          let suffixY = ""
          if (suffix(file) === "png") {
            suffixY = "png"
          } else if (suffix(file) === "jpg") {
            suffixY = "jpeg"
          } else if (suffix(file) === "gif") {
            suffixY = "gif"
          }
          uploadApi.getUpload({ bucketName: "notice", objectName: file.name }).then(res => {
            uploadApi.uploadFile({ url: res.data.uploadPath, file: file }, "image/" + suffixY).then(data => {
              succFun(res.data.downloadPath)
            })
          })

          // callback('http
        },
        toolbar_sticky: true,
        autosave_ask_before_unload: false
      }
    }
  },
  watch: {
    tinymceHtml: {
      handler(val) {
        if (this.contentDetails) {
          this.Html = this.contentDetails + val
        } else {
          this.Html = val
        }
        this.$emit("echoEditor", this.Html)
      },
      immediate: true,
      deep: true
    },
    contentDetails: {
      handler(val) {
        this.Html = val
        this.$emit("echoEditor", this.Html)
      }
    }
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    echoEditor(data) {
      this.$store.commit("setHtml", data)
    }
    // echoEditor() {
    //   this.Html = tinymce.activeEditor.setContent();
    //   this.$store.commit("setHtml", this.Html)
    // }
  }
}
</script>
  1. 在需要的位置引入上面這個vue檔案,作為子元件使用

Vue中使用富文字外掛Tinymce

Vue中使用富文字外掛Tinymce

  1. 頁面展示

Vue中使用富文字外掛Tinymce

三:富文字tinymce獲取實時輸入資料看這篇文章



0則評論

您的電子郵件等資訊不會被公開,以下所有項目均必填

OK! You can skip this field.