tinymce富文本框在vue项目中的应用

在项目中应用tinymce富文本框的使用,首先安装tinymce、tinymce-vue这两个插件,

npm install tinymce -S

npm install @tinymce/tinymce-vue -S

安装完成之后在node_modules中找到tinymce文件夹中找到skins、jquery.tinymce.js、jquery.tinymce.min.js,之后安装中文语言包https://www.tiny.cloud/get-tiny/language-packages/;把这些文件放进public文件夹内,在components中新建Tinymce组件;在页面中引用跟正常组件一样引入注册使用就可以了。

<template>

  <div class="tinymce-editor">

    <editor

      v-model="myValue"

      :init="init"

      :api-key="apiKey"

      :disabled="disabled"

    />

  </div>

</template>

<script>

// import { fileUpload } from '@/api/cms'

import tinymce from "tinymce/tinymce";

import Editor from "@tinymce/tinymce-vue";

// import 'tinymce/themes/modern/theme'

import "tinymce/themes/silver/theme";

import "tinymce/icons/default/icons";

import "tinymce/plugins/image"; // 插入上传图片插件

import "tinymce/plugins/media"; // 插入视频插件

import "tinymce/plugins/table"; // 插入表格插件

import "tinymce/plugins/link"; // 超链接插件

import "tinymce/plugins/code"; // 代码块插件

import "tinymce/plugins/lists"; // 列表插件

import "tinymce/plugins/contextmenu"; // 右键菜单插件

import "tinymce/plugins/wordcount"; // 字数统计插件

import "tinymce/plugins/colorpicker"; // 选择颜色插件

import "tinymce/plugins/textcolor"; // 文本颜色插件

import "tinymce/plugins/fullscreen"; // 全屏

import "tinymce/plugins/help"; // 帮助

import "tinymce/plugins/charmap";

import "tinymce/plugins/paste";

import "tinymce/plugins/print"; // 打印

import "tinymce/plugins/preview"; // 预览

import "tinymce/plugins/hr"; // 水平线

import "tinymce/plugins/anchor";

import "tinymce/plugins/pagebreak";

import "tinymce/plugins/spellchecker";

import "tinymce/plugins/searchreplace";

import "tinymce/plugins/visualblocks";

import "tinymce/plugins/visualchars";

import "tinymce/plugins/insertdatetime";

import "tinymce/plugins/nonbreaking";

import "tinymce/plugins/autosave";

import "tinymce/plugins/fullpage";

import "tinymce/plugins/toc";

import "tinymce/plugins/advlist";

import "tinymce/plugins/autolink";

import "tinymce/plugins/codesample";

import "tinymce/plugins/directionality";

import "tinymce/plugins/imagetools";

import "tinymce/plugins/noneditable";

import "tinymce/plugins/save";

import "tinymce/plugins/tabfocus";

import "tinymce/plugins/textpattern";

import "tinymce/plugins/template";

export default {

  components: {

    Editor,

  },

  props: {

    // 传入一个value,使组件支持v-model绑定

    value: {

      type: String,

      default: "",

    },

    disabled: {

      type: Boolean,

      default: false,

    },

    plugins: {

      type: [String, Array],

      default:

        "lists image media table textcolor wordcount contextmenu preview",

    },

    toolbar: {

      type: [String, Array],

      default:

        "undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat table| fontsizeselect | fontselect'",

    },

  },

  data() {

    return {

      apiKey: "jzlds2e6urz6akm9wxp4f70mnwg83d8fovsialqazxowyity",

      // 配置文件服务器的静态访问路径前缀

      // static_web_preurl: 'http://localhost/files/hxzy_img/',

      // 初始化配置

      init: {

        placeholder: "请输入内容",

        // language_url: require("../assets/langs/zh-Hans.js"), // 这个文件会放在下面

        language_url: require("../../../public/tinymce/langs/zh_CN"),

        language: "zh_CN",

        skin_url: "/tinymce/skins/ui/oxide",

        height: 300,

        end_container_on_empty_block: true,

        powerpaste_word_import: "clean",

        advlist_bullet_styles: "square",

        advlist_number_styles: "default",

        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],

        default_link_target: "_blank",

        link_title: false,

        media_live_embeds: true,

        content_style: "img {max-width:100%;}", // 直接自定义可编辑区域的css样式

        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin

        // plugins: this.plugins,

        // toolbar: this.toolbar,

        // @ts-nocheckplugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',

        plugins:

          "advlist anchor autolink autosave code codesample colorpicker  contextmenu directionality  fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",

        // toolbar:'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat | table',

        toolbar: [

          "searchreplace bold italic underline strikethrough fontselect fontsizeselect  alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",

          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",

        ],

        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt", // 第二步

        font_formats:

          "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",

        branding: false,

        menubar: true,

        elementpath: false,

        file_picker_types: "media",

        // 此处为图片上传处理函数,这个直接用了base64的图片形式上传图片,

        // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler

        /* images_upload_handler: async(blobInfo, success, failure) => {

          //  let formdata = new FormData()

          // formdata.set('file', blobInfo.blob())

          const { url, name } = await this.uploadFile(blobInfo.blob(), 'image')

          success(url, { title: name })

          // this.handleImgUpload(blobInfo, success, failure)

        }*/

        // file_picker_callback: (cb, value, meta) => {

        //   // 当点击meidia图标上传时,判断meta.filetype == 'media'有必要,因为file_picker_callback是media(媒体)、image(图片)、file(文件)的共同入口

        //   if (meta.filetype == 'media') {

        //     // 创建一个隐藏的type=file的文件选择input

        //     const input = document.createElement('input')

        //     input.setAttribute('type', 'file')

        //     input.setAttribute('accept', 'video/*')

        //     input.onchange = async(e) => {

        //       const file = e.path[0].files[0]// 只选取第一个文件。如果要选取全部,后面注意做修改

        //       if (this.validateVideo(file)) {

        //         const { url, name } = await this.uploadFile(file, 'video')

        //         cb(url, { title: name })

        //       }

        //     }

        //     // 触发点击

        //     input.click()

        //   }

        // }

      },

      myValue: this.value,

    };

  },

  watch: {

    value(newValue) {

      this.myValue = newValue;

    },

    myValue(newValue) {

      this.$emit("input", newValue);

    },

  },

  mounted() {

    tinymce.init({});

  },

  methods: {

    // 校验视频

    /* async validateVideo(file) {

      const isMP4 = file.type === 'video/mp4'

      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isMP4) {

        this.$message.error('上传视频必须为 MP4 格式!')

        return false

      }

      if (!isLt3M) {

        this.$message.error('上传视频大小限制 3M 以内!')

        return false

      }

      // const duration = await this.getVideoDuration(file)

      // if (duration > 60) {

      //   this.$message.error('上传视频时长不能超过 60 秒!')

      //   return false

      // }

      return true

    },*/

    /**

     * @description 获取视频时长

     * @param {File} file - 要上传的文件

     * @returns {Promise<number>}

     */

    /*  getVideoDuration(file) {

      return new Promise(resolve => {

        const videoElement = document.createElement('video')

        videoElement.src = URL.createObjectURL(file)

        videoElement.addEventListener('loadedmetadata', () => {

          resolve(videoElement.duration)

        })

      })

    }*/

    /**

     * @description 上传文件

     * @param {File} file - 要上传的文件

     * @param {string} type - 文件类型

     * @returns {Object}

     */

    /*     async uploadFile(file, type = 'images') {

      const loading = this.$loading({

        lock: true,

        text: 'Loading',

        spinner: 'el-icon-loading',

        background: 'rgba(0, 0, 0, 0.7)'

      })

      const formData = new FormData()

      formData.append('file', file)

      // // 注:此为调用后端上传接口,需根据实际情况进行调整

      // const res = await fileUpload(formData)

      // loading.close()

      // if (res.code !== 1) return this.$message.error(res.$message)

      // return {

      //   url: `${ROOT}/${res.data}`,

      //   name: file.name

      // }

    },*/

    // 添加相关的事件,可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events

    // 需要什么事件可以自己增加

    onClick(e) {

      this.$emit("onClick", e, tinymce);

    },

    // 可以添加一些自己的自定义事件,如清空内容

    clear() {

      this.myValue = "";

    },

  },

};

</script>

<style scoped>

.tinymce-editor {

  width: 100%;

  height: 100%;

}

</style>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容