vue3 tinymce富文本插件
vue3 tinymce富文本
一、安装
中文官网:TinyMCE中文文档中文手册 (ax-z.cn)
我下载的版本是 5.10.2;
最新版本 6 地址 :TinyMCE 6 Documentation | TinyMCE Documentation
汉化包:找到中文的 下载就可以
我下载的 TinyMCE 6 语言包 ,但是表格那里有两个没有翻译,看了一下汉化包,里面没有那两个的翻译,自己手动加的。
下载完成后,在 public 文件夹下 新建 tinymce 文件夹,把下载的语言包放在下面,
lang.js
里面是 Unicode编码,要改的话 去这个链接 在线转换在线中文汉字/ASCII码/Unicode编码互相转换工具 - 编码转换工具 - 脚本之家在线工具 (jb51.net)
二、使用
src/components里 新建 Editor.vue
父组件里引入
<TEditor ref="editor" v-model="data.leafDetail" @saveContent='saveContent'/>
import TEditor from '@/components/Editor.vue';
// 点击富文本中的保存按钮
const saveContent = (val: any) => {
console.log(val, 'val')
}
子组件 Editor.vue
插件比较全的 https://www.cnblogs.com/huihuihero/p/13877589.html
我的不全,有一些功能用不到就没有写
有一些重复的功能,能去掉的也都去掉了,只保留了一个,还有没研究明白的也都去掉了,解决不掉提出的问题,那就解决掉问题来源。
<template>
<div class="tinymce-box">
<Editor id="myedit" v-model="content" :init="init" tag-name="div" :disabled="disabled" @onClick="onClick" />
</div>
</template>
<script>
// import api from '../api/api.js'
//引入tinymce编辑器
import Editor from '@tinymce/tinymce-vue';
//引入方式引入node_modules里的tinymce相关文件文件
import tinymce from 'tinymce/tinymce'; //tinymce默认hidden,不引入则不显示编辑器
import 'tinymce/themes/silver'; //编辑器主题,不引入则报错
import 'tinymce/icons/default'; //引入编辑器图标icon,不引入则不显示对应图标
// import "tinymce/tinymce.min.js"; //入口文件
// import "tinymce/themes/silver/theme.min.js"; //主题文件,不引入你在界面上看不到编辑器,浏览器会把它隐
// //藏,不相信你就别引入看看界面效果就知道了
// import "tinymce/icons/default/icons.min.js" //图标文件
// import "tinymce/plugins/print/plugin.min.js"
// import "tinymce/plugins/code/plugin.min.js"
// import "tinymce/plugins/table/plugin.min.js"
// import "tinymce/plugins/image/plugin.min.js"
// import "tinymce/plugins/preview/plugin.min.js"
// import "tinymce/plugins/fullscreen/plugin.min.js"
// 引入编辑器插件
import 'tinymce/plugins/advlist'; //高级列表
import 'tinymce/plugins/anchor'; //锚点
import 'tinymce/plugins/autolink'; //自动链接
// import 'tinymce/plugins/autoresize'; //编辑器高度自适应,注:plugins里引入此插件时,Init里设置的height将失效
import 'tinymce/plugins/autosave'; //自动存稿
// import 'tinymce/plugins/charmap'; //特殊字符
import 'tinymce/plugins/code'; //编辑源码
import 'tinymce/plugins/codesample'; //代码示例
import 'tinymce/plugins/directionality'; //文字方向
// import 'tinymce/plugins/emoticons'; //表情
// import 'tinymce/plugins/fullpage'; //文档属性
import 'tinymce/plugins/fullscreen'; //全屏
import 'tinymce/plugins/help'; //帮助
import 'tinymce/plugins/hr'; //水平分割线
import 'tinymce/plugins/image'; //插入编辑图片
// import 'tinymce/plugins/importcss'; //引入css
import 'tinymce/plugins/insertdatetime'; //插入日期时间
import 'tinymce/plugins/link'; //超链接
import 'tinymce/plugins/lists'; //列表插件
import 'tinymce/plugins/indent2em'; //缩进
import 'tinymce/plugins/media'; //插入编辑媒体
import 'tinymce/plugins/nonbreaking'; //插入不间断空格
import 'tinymce/plugins/pagebreak'; //插入分页符
import 'tinymce/plugins/paste'; //粘贴插件
import 'tinymce/plugins/preview'; //预览
// import 'tinymce/plugins/print'; //打印
import 'tinymce/plugins/quickbars'; //快速工具栏
import 'tinymce/plugins/save'; //保存
import 'tinymce/plugins/searchreplace'; //查找替换
// import 'tinymce/plugins/spellchecker' //拼写检查,暂未加入汉化,不建议使用
// import 'tinymce/plugins/tabfocus'; //切入切出,按tab键切出编辑器,切入页面其他输入框中
import 'tinymce/plugins/table'; //表格
// import 'tinymce/plugins/template'; //内容模板
import 'tinymce/plugins/textcolor'; //文字颜色
import 'tinymce/plugins/textpattern'; //快速排版
// import 'tinymce/plugins/toc'; //目录生成器
// import 'tinymce/plugins/visualblocks'; //显示元素范围
// import 'tinymce/plugins/visualchars'; //显示不可见字符
// import 'tinymce/plugins/wordcount'; //字数统计
import {
onMounted
} from '@vue/runtime-core';
import {
ref,
watch,
getCurrentInstance
} from 'vue';
import {
ElMessage,
} from 'element-plus'
export default {
name: 'TEditor',
components: {
Editor,
},
props: {
modelValue: {
type: String,
default: '',
},
disabled: {
type: Boolean,
default: false,
},
plugins: {
type: [String, Array],
// default: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave ',
default: 'save preview searchreplace autolink directionality fullscreen image link code codesample table hr pagebreak nonbreaking anchor insertdatetime advlist lists imagetools media textpattern help autosave indent2em formatpainter axupimgs ',
},
toolbar: {
type: [String, Array],
// default: 'fullscreen 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 | code selectall | indent2em lineheight formatpainter axupimgs',
default: ' save code undo redo restoredraft | cut copy paste pastetext | link anchor | outdent indent | bullist numlist | \
pagebreak insertdatetime | fullscreen | indent2em formatpainter axupimgs'
},
height: {
type: Number,
default: 500,
},
},
emits: {
'update:modelValue': null,
'saveContent': ''
},
setup(props, context) {
const $post = getCurrentInstance()?.appContext.config.globalProperties.$post;
const content = ref();
watch(
() => props.modelValue,
(initInfo, prevInitInfo) => {
content.value = props.modelValue;
},
);
watch(
() => content.value,
(initInfo, prevInitInfo) => {
revert_data(content);
},
);
const init = {
language_url: '/tinymce/langs/zh_CN.js', //引入语言包文件
language: 'zh_CN', //语言类型
skin_url: '/tinymce/skins/ui/oxide', //皮肤:浅色
// skin_url: '/tinymce/skins/ui/custom', //皮肤:浅色 自定义
// content_css: '/tinymce/skins/ui/custom/content.min.css', // 自定义
// icons_url: '/tinymce/design/icons.js', // load icon pack
// icons: 'design' , // baseURL/icons/custom/icons.js
// skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤:暗色
plugins: props.plugins, //插件配置
toolbar: props.toolbar, //工具栏配置,设为false则隐藏
save_enablewhendirty: false,
save_onsavecallback: function () {
// console.log('已保存');
context.emit('saveContent', content);
},
default_link_target: "_blank",
toolbar_mode: 'sliding',
menubar: 'file edit insert view format table', //菜单栏配置,设为false则隐藏,不配置则默认显示全部菜单,也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”
menu: {
// file: { title: '文件', items: 'newdocument' },
edit: {
title: '编辑',
items: 'undo redo | cut copy paste pastetext | selectall'
},
insert: {
title: '插入',
items: 'link image media | hr'
},
view: {
title: '查看',
items: 'visualaid'
},
// format: {
// title: '格式',
// items:
// 'bold italic underline strikethrough superscript subscript | formats | removeformat',
// },
// table: { title: '表格', items: 'inserttable tableprops deletetable | cell row column' },
// tools: { title: '工具', items: 'spellchecker code' },
},
hidden_input: false,
fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 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;',
height: props.height, //注:引入autoresize插件时,此属性失效
placeholder: '在这里输入文字',
branding: false, //tiny技术支持信息是否显示
resize: false, //编辑器宽高是否可变,false-否,true-高可变,'both'-宽高均可,注意引号
statusbar: false, //最下方的元素路径和字数统计那一栏是否显示
elementpath: false, //元素路径是否显示
contextmenu_never_use_native: true, // 屏蔽浏览器本身的右键菜单
draggable_modal: true, // 模态窗口添加拖动模式。默认是关闭的。 *****不好使
content_style: 'img {max-width:100%;}', //直接自定义可编辑区域的css样式
// content_css: '/tinycontent.css', //以css文件方式自定义可编辑区域的css样式,css文件需自己创建并引入
// images_upload_url: '/demo/upimg.php', //后端处理程序的url
// images_upload_base_path: '/demo', //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
// 此处为图片上传处理函数,这个直接用了base64的图片形式上传图片,
// 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
media_alt_source: false,
// 自己项目需要 封装axios 上传的
images_upload_handler: (blobInfo, success, failure) => {
var file = blobInfo.blob(); //转化为易于理解的file对象
var formDatas;
formDatas = new FormData();
formDatas.append('file', file, file.name);
$post("url", formDatas).then((res) => {
if (res.ResultCode == '0000') {
success(res.Data.location);
}
});
// 官网给的上传的例子
// xhr = new XMLHttpRequest();
// xhr.withCredentials = false;
// xhr.open('POST', 'File/UpFileReturnUrl');
// xhr.onload = function () {
// var json;
// if (xhr.status != 200) {
// // failure('HTTP Error: ' + xhr.status);
// return;
// }
// json = JSON.parse(xhr.responseText);
// console.log(json, 'json');
// if (!json || typeof json.Data.location != 'string') {
// // failure('Invalid JSON: ' + xhr.responseText);
// return;
// }
// success(json.Data.location);
// };
// formData = new FormData();
// formData.append('file', file, file.name); //此处与源文档不一样
// xhr.send(formData);
},
media_poster: false, //显示隐藏图片封面输入框
file_picker_types: 'file image media',
// 上传 图片 文件 视频
file_picker_callback: function (callback, value, meta) {
//文件分类
var filetype =
'.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
//为不同插件指定文件类型及后端地址
switch (meta.filetype) {
case 'image':
filetype = '.jpg, .jpeg, .png, .gif';
// upurl = 'upimg.php';
break;
case 'media':
filetype = '.mp3, .mp4';
// upurl = 'upfile.php';
break;
case 'file':
default:
}
//模拟出一个input用于添加本地文件
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', filetype);
input.click();
// 自己项目需要 封装axios 上传的 并且做了上传大小限制
input.onchange = function () {
var file = this.files[0];
if(file.size >104857600){
ElMessage.error('上传文件不能超过100M')
}else{
var formData;
formData = new FormData();
formData.append('file', file, file.name);
$post("url", formData).then((res) => {
if (res.ResultCode == '0000') {
callback(encodeURI('/file/'+res.Data.location), {
title: file.name
});
}
});
}
// 官网给的上传的例子
// xhr = new XMLHttpRequest();
// xhr.withCredentials = false;
// xhr.open('POST', upurl);
// xhr.onload = function () {
// var json;
// if (xhr.status != 200) {
// console.log(xhr, 123);
// // failure('HTTP Error: ' + xhr.status);
// return;
// }
// json = JSON.parse(xhr.responseText);
// console.log(json, 'json');
// if (!json || typeof json.Data.location != 'string') {
// console.log(123);
// // failure('Invalid JSON: ' + xhr.responseText);
// return;
// }
// console.log(json.Data.location, 'json.location');
// // callback(json.location);
// callback(encodeURI(json.Data.location), {
// title: file.name
// });
// };
// formData = new FormData();
// formData.append('file', file, file.name);
// xhr.send(formData);
//下方被注释掉的是官方的一个例子
//放到下面给大家参考
/*var reader = new FileReader();
reader.onload = function () {
// Note: Now we need to register the blob in TinyMCEs image blob
// registry. In the next release this part hopefully won't be
// necessary, as we are looking to handle it internally.
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
// call the callback and populate the Title field with the file name
callback(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);*/
};
},
// 视频上传完成 回调 ,根据需要看能不能用上
media_url_resolver: (data, resolve) => {
// console.log(data, 'dataaaa');
// console.log(resolve, 'resolve');
// try {
// let videoUri = encodeURI(data.url);
// if(data.url.indexOf('.mp4')>-1) {
// // 判断是否mp4 否则用ifarme嵌套
// let embedHtml = `<p>
// <video src=${ data.url } width="100%" height="auto" style="max-width: 100%;" allowfullscreen="false" controls="controls" controlslist="nodownload">
// </video>
// </p>`;
// resolve({ html: embedHtml });
// }else {
// let embedHtml = `<p>
// <iframe frameborder="0" src=${ data.url } width="100%" height="100%" style="max-width: 100%;">
// </iframe>
// </p>`;
// resolve({ html: embedHtml });
// }
// } catch (e) {
// resolve({ html: "" });
// }
},
};
tinymce.init; // 初始化
const revert_data = content => {
context.emit('update:modelValue', content);
};
// 添加相关的事件,可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
// 需要什么事件可以自己增加
function onClick(e) {
this.$emit('onClick', e, tinymce);
}
// 可以添加一些自己的自定义事件,如清空内容
function clear() {
// this.contentValue = '';
}
const setEditMode = type => {
tinymce.editors['myedit'].setMode(type); //开启只读模式
};
onMounted(() => {
// readonly();
});
return {
content,
init,
revert_data,
onClick,
clear,
setEditMode,
// contentValue: this.value,
};
},
};
</script>
<style lang="less" scoped>
</style>
三、自定义部分
自定义的主要是 主题和图标
主题:
主题可以通过 skin.tiny.cloud/t5/ 设置想要的颜色
设置完成后,右上角 Get Skin 下载,解压后的两个文件
放在 public/tinymce 下
init 初始化里 ,需要把原来默认的主题注销,换上新下载的文件路径
图标:
把 node_modules\tinymce\icons\default 文件夹复制出来一份,放在 public/tinymce 下面,须重命名,例如 重命名为 design
打开 design\icons.js
这个名字 必须换成重命名后的名字,不能用原来的 default
里面的图标 默认对应的名字参考:tinymce(Version: 5.0.4)内含icon对照表_月晕而风础润而雨的博客-CSDN博客_tinymce 图标
图标是svg 格式,其他格式不可以,阿里图标库 icon大全 可以选择,直接复制 svg 格式,替换掉文件夹里对应的路径,宽高也要设置,替换掉没有显示的话,重启一下项目,(本地的svg图片,还没研究明白怎么替换,再研究研究)
把这个默认图标 注销
注意名字!!!
如果是改圆角 边框什么的,直接改样式就行
/deep/ .tox-tinymce{
border-radius: 20px;
border: 1px solid blue;
}
补充:新版本的会有这个标志,是tiny的促销标志
在 initOptions 里加上 promotion: false 就可以隐藏掉
更多推荐
所有评论(0)