代码实现方式:
<template>
<div>
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editor"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
style="height: 300px"
v-model="html"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="onCreated"
@onChange="onChange"
@onDestroyed="onDestroyed"
@onMaxLength="onMaxLength"
@onFocus="onFocus"
@onBlur="onBlur"
@customAlert="customAlert"
@customPaste="customPaste"
/>
</div>
</template>
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Boot } from '@wangeditor/editor'
class MyButtonMenu {
constructor(vueInstance) {
this.vueInstance = vueInstance;
this.title = '编辑源代码'; // 自定义菜单标题
this.iconSvg = '<svg></svg>'; // 可选 菜单图标
this.tag = 'button'; // 自定义菜单的 HTML 标签
}
// 获取菜单执行时的 value,返回空字符串或 false
getValue(editor) {
return ''; // 默认返回空
}
// 菜单是否需要激活(如选中加粗文本,“加粗”菜单会激活),用不到则返回 false
isActive(editor) {
return false; // 默认不激活
}
// 菜单是否需要禁用(如选中 H1,“引用”菜单被禁用),用不到则返回 false
isDisabled(editor) {
return false; // 默认不禁用
}
// 点击菜单时触发的函数
exec(editor, value) {
if (this.isDisabled(editor)) return;
this.vueInstance.editHTML();
}
}
export default {
name: 'MyEditorComponent',
components: { Editor, Toolbar },
data() {
return {
toolbarConfig: {
insertKeys: {
index: 0,
keys: ['editCode']
}
},
html: '', // 用于绑定编辑器内容的变量
editorConfig: {}, // 编辑器配置
mode: 'default', // 编辑器模式
editor: null // 编辑器实例
}
},
created() {
const menu1Conf = {
key: 'editCode', // 定义唯一的 menu key
factory: () => new MyButtonMenu(this) // 使用箭头函数以避免 `this` 问题
};
Boot.registerMenu(menu1Conf);
},
methods: {
onCreated(editor) {
this.editor = editor; // 保存编辑器实例
},
onChange() {
// 自定义的 change 处理逻辑
},
onDestroyed() {
// 自定义的 destroyed 处理逻辑
},
onMaxLength() {
// 自定义的 maxLength 处理逻辑
},
onFocus() {
// 自定义的 focus 处理逻辑
},
onBlur() {
// 自定义的 blur 处理逻辑
},
customAlert() {
// 自定义的 alert 处理逻辑
},
customPaste() {
// 自定义的 paste 处理逻辑
},
editHTML() {
// 自定义的 HTML 编辑逻辑
}
}
}
</script>
<style scoped>
/* 样式优化,可以根据需要添加或修改 */
</style>
到这里配置好了按钮已经加上去了