Vue3 中使用富文本编辑器(wangEditor)

4,958 阅读1分钟

支持 Vue3 的富文本编辑器有很多,wangEditor 就是其中之一、尝试过其它的富文本编辑器,或多或少都会遇到一些坑,wangEditor 使用起来比较顺畅,它的配置相对比较简单,编辑器的风格也很简单,并且不依赖任何第三方框架(JS、Vue、React 都可以使用)。

引入 wangEditor 后的效果如下:

image.png

安装

安装时需要执行两条指令,如果是 vue 框架需要执行第二条指令:

npm install @wangeditor/editor --save
npm install @wangeditor/editor-for-vue --save

封装编辑器组件

由于 wangEditor 工具栏配置和菜单配置(如配置颜色、字体等)是分离的,并且一个项目中可能会在多个页面中使用富文本编辑器,所以封装成通用组件之后后再使用。

  • Toolbar:工具栏
  • Editor: 编辑器
  • default-config: 配置项
  • getHtml() 获取编辑器中的内容数据

image.png

实现代码如下:

<Toolbar
  :editor="editorRef"
  :default-config="toolbarConfig"
  mode="default"
/>
<Editor
  v-model="modelValue"
  :default-config="editorConfig"
  mode="default"
  @on-change="handleChange"
  @on-created="handleCreated"
/>

引入并且使用:

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const props = defineProps({
  modelValue: {
    type: [String],
    default: ""
  },
});
const emit = defineEmits(["update:modelValue"]);
const editorRef = shallowRef();
const toolbarConfig = ref({});
const editorConfig = ref({
  placeholder: "请输入..."
});
const handleCreated = (editor: any) => {
  editorRef.value = editor;
};
function handleChange(editor: any) {
 modelValue.value = editor.getHtml();
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

注:如果遇到修改编辑器内容但数据不更新的问题,可以在触发 on-change 事件的时候将数据 emit 到父组件中,再重新赋值

除此之外 wangEditor 还支持通过 CSS vars 自定义主题,或是国际化(语言切换),具体可参考 wangEditor 文档

使用

image.png

image.png

输入内容后,获取到的数据如下:

image.png