选择一个合适的富文本编辑器对于一个前端项目至关重要,这次我基于Vue来开发我项目中的前端部分,经过权衡选择了tinymce。其在UI,功能都很适合,tinymce官方文档:点击打开链接;
- 引入tinymce 我选用的版本4.7.4
npm install tinymce -S
- 将tinymce创建为Vue的组件,便于日后复用,创建组件editor.vue
<template>
<textarea :id="id" :value="value"></textarea>
</template>
<script>
// Import TinyMCE
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/modern/theme';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/link';
const INIT = 0;
const CHANGED = 2;
var EDITOR = null;
export default {
props: {
value: {
type: String,
required: true
},
setting: {}
},
watch: {
value: function (val) {
console.log('init ' + val)
if (this.status == INIT || tinymce.activeEditor.getContent() != val){
tinymce.activeEditor.setContent(val);
}
this.status = CHANGED
}
},
data: function () {
return {
status: INIT,
id: 'editor-'+new Date().getMilliseconds(),
}
},
methods: {
},
mounted: function () {
const _this = this;
const setting =
{
selector:'#'+_this.id,
language:"zh_CN",
init_instance_callback:function(editor) {
EDITOR = editor;
console.log("Editor: " + editor.id + " is now initialized.");
editor.on('input change undo redo', () => {
var content = editor.getContent()
_this.$emit('input', content);
});
},
plugins:[]
};
Object.assign(setting,_this.setting)
tinymce.init(setting);
},
beforeDestroy: function () {
tinymce.get(this.id).destroy();
}
}
</script>
在钩子mounted 进行了tinymce的初始化工作,调用 tinymce.init(setting),setting为配置信息这样我们便初步配置完成了editor组件
- 在其他页面使用组件
<template>
<div class="app-container">
<div>
<!-- 组件有两个属性 value 传入内容双向绑定 setting传入配置信息 -->
<editor class="editor" :value="content" :setting="editorSetting" @input="(content)=> content = content"></editor>
</div>
</div>
</template>
<script>
import editor from '@/components/editor'
export default {
name: "editor-demo",
data: function () {
return {
content:'我是富文本编辑器的内容',
//tinymce的配置信息 参考官方文档 https://www.tinymce.com/docs/configure/integration-and-setup/
editorSetting:{
height:400,
}
}
},
components:{
'editor':editor
}
}
</script>
<style scoped>
</style>