tinymce富文本的使用

430 阅读3分钟

官网地址:www.tiny.cloud/docs/

前端框架:vue

一 打开官网,选择v4版本(免费)

image.png

image.png

image.png 点击这里下载源代码 image.png

image.png

image.png

点击这里下载汉化包

image.png

image.png 解压后放在public目录下

image.png

配置index.html文件,导入代码

image.png

然后就可以使用了,先创建一个简单的富文本编辑器

<template>
  <div style="padding: 30px">
    <textarea id="NContent"></textarea>
  </div>
</template>
<script>
export default {
  mounted() {
    tinymce.init({
      selector: "#NContent",
      auto_focus: "Content",
      content_style: "img{width:100%;height: auto;}",
      branding: false,
      height: 220,
    });
  },
};
</script>

image.png

配置工具栏,不配置默认是有这几个功能

image.png 这是我的所有代码配置

  mounted() {
      tinymce.init({
        selector: "#NContent",
        auto_focus: "Content",
        content_style: "img{width:100%;height: auto;}",
        branding: false,
        height: 220,
        theme: "modern",
        add_unload_trigger: false,
        image_advtab: true,
        automatic_uploads: false,
        plugins: [
          "advlist autolink lists link image imagetools charmap preview",
          "searchreplace visualblocks fullscreen",
          "insertdatetime media table contextmenu paste",
          "emoticons textcolor",
        ],
        toolbar1:
          "undo redo | styleselect | fontselect | fontsizeselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent",
        toolbar2:
          "forecolor backcolor table emoticons link image imagetools media | fullscreen preview |  ",

        //TinyMCE 会将所有的 font 元素转换成 span 元素
        convert_fonts_to_spans: true,
        //换行符会被转换成 br 元素
        convert_newlines_to_brs: false,
        //在换行处 TinyMCE 会用 BR 元素而不是插入段落
        force_br_newlines: false,
        //当返回或进入 Mozilla/Firefox 时,这个选项可以打开/关闭段落的建立
        force_p_newlines: false,
        //这个选项控制是否将换行符从输出的 HTML 中去除。选项默认打开,因为许多服务端系统将换行转换成 <br />,因为文本是在无格式的 textarea 中输入的。使用这个选项可以让所有内容在同一行。
        remove_linebreaks: false,
        //不能把这个设置去掉,不然图片路径会出错
        relative_urls: false,
        //不允许拖动大小
        resize: true,

        font_formats:
          "宋体=宋体;黑体=黑体;仿宋=仿宋;楷体=楷体;隶书=隶书;幼圆=幼圆;Arial=arial,helvetica,sans-serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats",
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
      });
  },

image.png

配置图片上传 images_upload_handler:

这里用的是XMLHttpRequest请求,可以自行用axios库请求

 data() {
    return {
      upfile: process.env.VUE_APP_CAS_SERVER + `/center/fileupload/upfile`, //后端上传图片地址
      imgBaseUrl: '' //查看图片前缀
    };
  },
  mounted() {
      tinymce.init({
        selector: "#NContent",
        auto_focus: "Content",
        content_style: "img{width:100%;height: auto;}",
        branding: false,
        .....
         images_upload_handler: (blobInfo, success, failure) => {
          let xhr, formData;
          // let stuId = ${user.userId};
          // let maxLogId = ${maxLogId};
          let myId = "joel";
          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open("POST", `${this.upfile}`); 
          xhr.setRequestHeader("Authorization", `bearer ${getToken()}`);  //设置请求头
          formData = new FormData();
          formData.append("file", blobInfo.blob());  //请求体 file属性
          formData.append("mn", "image");            //请求体 其他属性,看后端传参要求
          xhr.onload = function (e) {
            let json;

            if (xhr.status != 200) {
              failure("HTTP Error: " + xhr.status);
              return;
            }
            json = JSON.parse(this.responseText);
            if (!json || typeof json.id != "string") {
              failure("Invalid JSON: " + xhr.responseText);
              return;
            }
            console.log(json)   //后端返回的数据
            success(imgBaseUrl + json.url);   //最终展示到页面上的图片url,前缀 + 返回的路径
          };
          xhr.send(formData);
        },
      });
  },

image.png

image.png

image.png

随便编辑一段内容,制作html模板发送给后端

1.创建html基础模板 创建htmlTem.js文件,导出两个html字符串

export const beforH = `<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body,
        html {
            padding: 0;
            margin: 0;
        }

        img {
            width: 100%;
            height: auto;
        }
    </style>
</head>

<body>
    <div style="padding: 0 10px;">`;

export const afterH = `</div>

  </body>

  </html>`;

页面新增提交按钮,点击按钮调用此方法

<template>
  <div style="padding: 30px">
    <textarea id="NContent"></textarea>
  </div>
  <button @click="submit">提交</button>
</template>
<script>
import { beforH, afterH } from "@/utils/htmlTem";
methods: {
    submit() {
      let htmlStr = beforH + tinyMCE.activeEditor.getContent() + afterH; //拼接后的html字符串
      //发送给后端
      uphtml({ html: htmlStr })
        .then(() => {
          this.$message.success("上传html成功");
        })
        .catch((error) => {
          reject(error);
        });
    },
  },
  </script>

举个栗子:

image.png

image.png 到此结束,

附件:

1.工具栏配置大全

image.png

tinymce.init({
  selector: '#NContent',
  // 工具栏1
  toolbar1: 'undo redo | styleselect | bold italic | link image',
  // 工具栏2
  toolbar2: 'alignleft aligncenter alignright',
})

所属插件为核心的项为基本包里自带的功能,直接写在toolbar里就可以,
属于插件的项需要引入插件(plugins: '插件名')然后在toolbar中配置。

插件配置表请看这篇文章 原文链接:blog.csdn.net/zjiang1994/…