这篇帖子主要是想介绍一下如何在vue3+ts中安装wangEditor编辑器,其实如何安装引入使用在官网里面已经介绍过。点击可查看vue3使用wangeditor。
主要也是我在实际练习过程中,模仿练习的过程中而碰到的问题。
一,安装
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue@next
# 或者 npm install @wangeditor/editor-for-vue@next --save
二,vue组件中引入
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('<p>hello</p>')
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
const handleCreated = (editor) => {
editorRef.value = editor // 记录 editor 实例,重要!
}
</script>
css的引入也可在style标签中:
<style src="@wangeditor/editor/dist/css/style.css"></style>
三,HTML模板
<template>
<div style="border: 1px solid #ccc">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="default"
/>
<Editor
style="height: 500px; overflow-y: hidden;"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="default"
@onCreated="handleCreated"
/>
</div>
</template>
至此,一个基本富文本编辑组件便出现了。但有些时候我们需要对该组件做一些自定义的配置,比如自定义上面的菜单栏,功能、顺序等,自定义编辑器、编辑选中操作栏等。
//工具栏配置 自定义编辑器上方的功能菜单
const toolbarConfig: Partial<IToolbarConfig> = {};
//编辑器配置
const editorConfig: Partial<IEditorConfig> = {
placeholder: "你好呀",
readOnly: false, //控制是否只读 默认为false 只读状态可通过 editor.enable() 和 editor.disable() 切换,
autoFocus: false, //配置编辑器默认是否 focus ,默认为 true
scroll: false, //配置编辑器是否支持滚动,默认为 true 。注意,此时不要固定 editor-container 的高度,设置一个 min-height 即可。
};
还有一些跟编辑有关的生命周期钩子函数和事件,具体也可参考官网,这里说一下我按照官网操作时碰到的问题:
该图是官网的实例,其方法是写在编辑器的属性里面,我这样写后浏览器报错了,我用有道词典翻译了意思就是说改方法不能写在属性里面。
// 编辑器内容、选区变化时的回调函数。
let onChage = (editor: IDomEditor) => {
console.log("content", editor.children);
};
// 组件销毁时触发
let onDestroyed = (editor: IDomEditor) => {
console.log("组件被销毁了");
};
// 编辑器 focus 时的回调函数。
let onFocus = () => {
console.log("组件获取焦点");
};
// 编辑器 blur 时的回调函数。
let onBlur = () => {
console.log("组件失去焦点了");
};
// 粘贴数据时间发生时 可自定义粘贴逻辑
const customPaste = (editor: IDomEditor, event: ClipboardEvent, callback: Function) => {
// console.log("ClipboardEvent 粘贴事件对象", event);
};
这样,方法就会正常触发了。
最奇怪的一个问题就是,我在安装wangEditor组件时,@wangeditor目录下居然没有editor这个文件夹,只有一个editor-for-vue文件夹,试了好多次安装就是没有,最后我是从别人的项目中将该文件夹拷贝过去的,于是全部都可以正常运行了。
wangEditor的依赖包已上传至码云仓库:https://gitee.com/liu-yunshun/wang-editor_modules.git