wangEditor官网:www.wangeditor.com/
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue
# 或者 npm install @wangeditor/editor-for-vue --save
<template>
<div>
<div style="border: 1px solid #ccc;">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editor"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
style="height: 500px; overflow-y: hidden;"
v-model="html"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="onCreated"
/>
</div>
</div>
</template>
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot, DomEditor } 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;
// 获取选中的文本
const selectedText = editor.getSelectionText();
// 将选中的文本设置到 Vue 实例的数据属性中
this.vueInstance.selectedText = selectedText;
// 显示弹出层 这块可以调用自己的弹出层
// this.vueInstance.dialogVisible = true;
console.log('点击了添加标注按钮',this.vueInstance.selectedText)
}
}
export default {
components: { Editor, Toolbar },
data() {
return {
editor: null,
html: '<p>hello</p>',
toolbarConfig: {
excludeKeys: [
// 这里面可以写自己要的工具,其他不需要的就不写就可以
'group-video',
'redo',
'undo',
'group-image',
'insertTable',
'codeBlock',
'fullScreen',
'group-more-style',
'emotion',
'insertLink',
'divider',
'bulletedList',
'todo',
'numberedList',
'blockquote',
'headerSelect',
'group-indent',
'group-justify'
],
// 添加自定义菜单项customAnnotation
// toolbarKeys: ['customAnnotation'],
insertKeys: {
index: 0,
keys: ['add-myMark']
}
},
editorConfig: { placeholder: '请输入内容...' },
mode: 'default', // or 'simple'
}
},
methods: {
onCreated(editor) {
this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
},
},
created() {
const menu1Conf = {
key: 'add-myMark', // 定义唯一的 menu key
factory: () => new MyButtonMenu(this) // 使用箭头函数以避免 `this` 问题
};
const module = {
menus: [menu1Conf]
}
Boot.registerModule(module)
},
mounted() {
// 模拟 ajax 请求,异步渲染编辑器
setTimeout(() => {
this.html = '<p>这是一段文字这是一段文字</p>'
}, 1500)
},
beforeDestroy() {
const editor = this.editor
if (editor == null) return
editor.destroy() // 组件销毁时,及时销毁编辑器
}
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
</style>