VueJS 集成 Medium Editor的示例代码 (自定义编辑器按钮)

2020-06-12 21:24:32易采站长站整理

import rangy from 'rangy/lib/rangy-core.js'
import 'rangy/lib/rangy-classapplier'
import 'rangy/lib/rangy-highlighter'
import 'rangy/lib/rangy-selectionsaverestore'
import 'rangy/lib/rangy-textrange'
import 'rangy/lib/rangy-serializer'
const pHash = {
p1: { name: 'p1', class: 'fs-36' },
p2: { name: 'p2', class: 'fs-30' },
p3: { name: 'p3', class: 'fs-24' },
p4: { name: 'p4', class: 'fs-18' },
p5: { name: 'p5', class: 'fs-14' },
p6: { name: 'p6', class: 'fs-12' }
}
function pButtonCreator (p) {
return MediumEditor.Extension.extend({
name: p.name,
init: function () {
this.classApplier = rangy.createClassApplier(p.class, {
elementTagName: 'span',
normalize: false
})
this.button = this.document.createElement('button')
this.button.classList.add('medium-editor-action')
this.button.innerHTML = p.name
this.button.title = p.class
this.on(this.button, 'click', this.handleClick.bind(this))
},
getButton: function () {
return this.button
},
clearFontSize: function () {
MediumEditor.selection.getSelectedElements(this.document).forEach(function (el) {
if (el.nodeName.toLowerCase() === 'span' && el.hasAttribute('class')) {
el.removeAttribute('class')
}
})
},
handleClick: function (event) {
this.clearFontSize()
this.classApplier.toggleSelection()
// Ensure the editor knows about an html change so watchers are notified
// ie: <textarea> elements depend on the editableInput event to stay synchronized
this.base.checkContentChanged()
}
})
}
export default {
P1: pButtonCreator(pHash['p1']),
P2: pButtonCreator(pHash['p2']),
P3: pButtonCreator(pHash['p3']),
P4: pButtonCreator(pHash['p4']),
P5: pButtonCreator(pHash['p5']),
P6: pButtonCreator(pHash['p6'])
}

简单来说就是给选中的文字加一些 class (上面是 fs-xx 之类的),其中需要引一个鼠标选中的库 rangy,挺烦人的也是,然后在 text-editor 中这样用:

先实例化


import ButtonBuilder from './buttonBuilder'
var editorOptions = {
toolbar: {
buttons: ['bold', 'italic', 'underline', 'removeFormat', 'p3', 'p4', 'p5', 'p6'] },
buttonLabels: 'fontawesome', // use font-awesome icons for other buttons
extensions: {
p3: new ButtonBuilder.P3(),
p4: new ButtonBuilder.P4(),
p5: new ButtonBuilder.P5(),
p6: new ButtonBuilder.P6()
},
placeholder: false
}

再放到 editor 上


this.editor = new MediumEditor(this.$el, Object.assign({}, editorOptions, this.options))

当然上面实例化的步骤不一定要写到这个组件里面,配置 options 也可以从组件外传入