最近在做一个vue项目, 其中用到了富文本tinymce插件,界面上需要有多个编辑器, 界面如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/f029b487c799482d8d53c2c31e07ccad.png
这里点击添加按钮, 需要动态添加tinymce组件
页面的元素
// item是v-for循环中的对象
<div :id="`tinymceEditorId_${item.custId || item.id}`"></div>
添加之前这里需要先移除已有的实例:
removeAllEditor(){
for (let i = tinymce.editors.length - 1 ; i > -1 ; i--) {
let editorId = tinymce.editors[i].id;
tinyMCE.execCommand("mceRemoveEditor", true, editorId);
}
}
注意, 这里的tinymce,tinyMCE两个是全局变量, 不是我声明的, 是系统内置的
动态生成组件:
// 这里面有几个参数, custId是新添加的组件的标识,id是从数据库读出来的,编辑数据时这个变量有值, index是当前列表中的第几个元素
this.infoList.forEach((item,index,arr)=>{
this.initTinymce('tinymceEditorId_' + (item.custId || item.id),item.content, index)
})
initTinymce方法代码如下:
initTinymce(domId, content, index) {
this.$nextTick(() => {
let pasteImage = (source)=> {
let image = "<img src='" + source + "' data-mce-selected='1'></img>";
this.tinymce.execCommand('mceInsertContent', false, image);
}
let readPastedBlob = (blob) => {
if (blob) {
reader = new FileReader();
reader.onload = function (evt) {
pasteImage(evt.target.result);
};
reader.readAsDataURL(blob);
}
}
let pasteHandler = (e)=> {
let cbData;
if (e.clipboardData) {
cbData = e.clipboardData;
} else if (window.clipboardData) {
cbData = window.clipboardData;
}
if (e.msConvertURL) {
let fileList = cbData.files;
if (fileList.length > 0) {
for (let i = 0; i < fileList.length; i++) {
let blob = fileList[i];
console.log("Image blob: " + blob);
readPastedBlob(blob);
}
}
}
if (cbData && cbData.items) {
if ((text = cbData.getData("text/plain"))) {
// Text pasting is already handled
return;
}
for (let i = 0; i < cbData.items.length; i++) {
if (cbData.items[i].type.indexOf('image') !== -1) {
let blob = cbData.items[i].getAsFile();
readPastedBlob(blob);
}
}
}
}
tinymce.init({
selector: '#'+domId,
toolbar: 'undo redo | styleselect bold italic | table',
language: 'zh_CN',
menubar: false,
plugins: 'image paste ax_wordlimit table colorpicker textcolor',
height: 100,
paste_data_images: true,
setup: (editor) => {
editor.on('init', () => {
editor.setContent(content);
})
editor.on('change', (aaa)=>{
this.contentForm.contents[index].content = tinyMCE.activeEditor.getContent()
})
editor.on('paste', pasteHandler);
}
})
});
},