<template> <div class="quill-editor"> <div ref="editor"></div> </div> </template> <script> import Quill from "quill"; const defaultOptions = { theme: "snow", boundary: document.body, modules: { toolbar: [ ["bold", "italic", "underline", "strike"], ["blockquote", "code-block"], // [{ header: 1 }, { header: 2 }], // [{ list: "ordered" }, { list: "bullet" }], // [{ script: "sub" }, { script: "super" }], [{ indent: "-1" }, { indent: "+1" }], // [{ direction: "rtl" }], [{ size: ["small", false, "large", "huge"] }], // [{ header: [1, 2, 3, 4, 5, 6, false] }], // [{ color: [] }, { background: [] }], // [{ font: [] }], [{ align: [] }], ["clean"], // ["link", "image", "video"], ], }, // placeholder: "Insert text here ...", readOnly: false, }; export default { name: "RichTextEditor", props: { content: String, value: String, disabled: { type: Boolean, default: false, }, options: { type: Object, required: false, default: () => ({}), }, placeholder: { type: String, required: false, default: "Insert text here ...", }, }, data() { return { _options: {}, _content: "", defaultOptions, }; }, computed: { mode() { return this.$store.state.Status.mode; }, isDisable: { get() { return this.mode === "display" || this.disabled; }, }, }, mounted() { this.initialize(); }, beforeDestroy() { this.quill = null; delete this.quill; }, methods: { initialize() { if (this.$el) { // Options this._options = Object.assign( { placeholder: this.placeholder }, this.defaultOptions, this.options ); this.quill = new Quill(this.$refs.editor, this._options); this.quill.enable(false); if (this.value || this.content) { this.quill.pasteHTML(this.value || this.content); } if (!this.isDisable) { this.quill.enable(true); } this.quill.on("selection-change", (range) => { if (!range) { this.$emit("blur", this.quill); } else { this.$emit("focus", this.quill); } }); // 更新 this.quill.on("text-change", (delta, oldDelta, source) => { let html = this.$refs.editor.children[0].innerHTML; const quill = this.quill; const text = this.quill.getText(); if (html === "<p><br></p>") html = ""; this._content = html; this.$emit("input", this._content); this.$emit("change", { html, text, quill }); }); this.$emit("ready", this.quill); } }, }, watch: { content(newVal, oldVal) { if (this.quill) { if (newVal && newVal !== this._content) { this._content = newVal; this.quill.pasteHTML(newVal); } else if (!newVal) { this.quill.setText(""); } } }, value(newVal, oldVal) { if (this.quill) { if (newVal && newVal !== this._content) { this._content = newVal; this.quill.pasteHTML(newVal); } else if (!newVal) { this.quill.setText(""); } } }, isDisable(newVal, oldVal) { if (this.quill) { this.quill.enable(!newVal); } }, }, }; </script> <style> .ql-toolbar.ql-snow .ql-formats { line-height: 1; } .ql-editor { min-height: 200px; max-height: 500px; } </style>