Vue3集成自定义富文档编辑器CKeditor
需求是要在vue3里集成一个富文档编辑器。需要基础文字格式编辑功能,对数学公式编辑要求较高。
WangEditor: 国人开发,轻量,兼容性很好,但是暂时还没有数学公式编辑功能。
Quill vue:文档全面,但是由于很久没有人维护更新,虽然有数学公式编辑功能,但框很小,不易编辑。
CKeditor: 有很好的团队维护,功能很全,也有数学辑功能,自定义功能接口很完备。由于CKeditor5 中的mathtype 收费(经费有限,所以就不整了,反正ckeditor4 也不错),所以决定使用ckeditor4.
首先去官网https://ckeditor.com/ckeditor-4/download/
按照自己需求选择一个版本,也可以点customize 自己配置想要的功能
如果是基础版可以直接使用npm install ckeditor4-vue
详见 https://ckeditor.com/docs/ckeditor4/latest/guide/dev_vue.html#basic-usage
如果是自定义的包按如下步骤
配置完功能按照指引下载后,会得到打包文件。将里面的所有文件都解压到<项目名>/public/ 下
项目名
public
ckeditor4
ckeditor4.js
config.js
libs
src
然后在index.html 中引入 js
<script src="<root>/public/ckeditor/ckeditor.js"></script>
可以有很多方式使用,这里采用独立组件方式
editor.vue
<template>
<textarea id = 'editor1' name="editor1">
</textarea>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref} from "vue";
declare const window: any;
export default defineComponent({
name:'ckeditor',
props:["content"],
setup(props,{emit}){
console.log("---start child component----")
let ckEditor: any;
onMounted(()=>{
ckEditor = window.CKEDITOR.replace("editor1"); //先渲染指定textarea
const t = ref(props.content); //从父组件拿到动态值
ckEditor.setData(t.value)
ckEditor.on('change', ()=>{ //监听内容的变化,并传递给父组件
emit('sendContent', ckEditor.getData())
})
})
}
})
</script>
parent.vue
<template>
<ckeditor
:content="txt"
@sendContent = 'updateContent'
/>
</template>
<script lang = "ts">
import { defineComponent, onMounted, ref} from 'vue';
import ckeditor from './ckeditor4.vue';
export default defineComponent({
name: 'AdminDoc',
components:{
ckeditor
},
setup() {
const txt = ref();
txt.value = ''; // 给内容赋值
const updateContent = (val: any)=>{ //更新内容
txt.value = val;
}
return {
txt
}
}
});
</script>
需要注意一点:在前后端传递数据的时候,有些内容很大,导致子组件在set value 的时候,并没有拿到最新的值,所以导致数据没有及时更新。因为在渲染子组件的时候,子组件onmounted 会优先执行。解决办法是将设置异步函数 async+ await 函数等待父组件拿到内容再执行。具体可以参见vue3 子父组件的异步方法。
@星心火
一名AI算法工程师/全栈工程师,永在科学的前沿砥砺前行
个人网站:www.wikizhi.com