vue3使用VueQuill插入自定义按钮
在 Vue 3 项目中使用 VueQuill
编辑器时,我们可以自定义内容来满足特定的需求。
本文将介绍如何在 VueQuill
中插入自定义内容,比如插入特定的标签或样式元素。
1. 项目设置和依赖安装
如果你还没有创建 Vue 3 项目,可以使用以下命令来初始化项目:
1 | npm init vue@latest |
选择 Vue 3 的相关配置,然后进入项目目录并安装依赖项。
安装 VueQuill
1 | npm install @vueup /vue-quill |
此库是 Quill 编辑器的 Vue 3 兼容版本。
2. 基础配置 VueQuill
在 src/components
中创建一个 QuillEditor.vue
文件,并引入 vue3-quill
,将 VueQuillEditor
作为编辑器组件使用。
-
template
内容
1 2 3 | < div class = "editor" > </ div > |
-
options
内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import '@vueup/vue-quill/dist/vue-quill.snow.css' ; import { Quill } from '@vueup/vue-quill' ; const options = ref({ theme: 'snow' , bounds: document.body, debug: 'warn' , modules: { // 工具栏配置 toolbar: { container: [ [ 'bold' , 'italic' , 'underline' , 'strike' ], // 加粗 斜体 下划线 删除线 [ 'blockquote' , 'code-block' ], // 引用 代码块 [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表 [{ indent: '-1' }, { indent: '+1' }], // 缩进 [{ size: [ 'small' , false , 'large' , 'huge' ] }], // 字体大小 [{ header: [1, 2, 3, 4, 5, 6, false ] }], // 标题 [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色 [{ align: [] }], // 对齐方式 [ 'clean' ], // 清除文本格式 [ 'link' , 'image' , 'video' ], // 链接、图片、视频 [ 'newFunction' ] // 新添加的按钮 ], handlers: { newFunction: (value: boolean) => { // 添加处理方法 const quill = quillEditorRef.value.getQuill(); // 插入自定义按钮 quill.insertEmbed(0, 'customSpan' , 'test' ); } } } }, placeholder: props.readOnly ? '' : '请输入内容' , readOnly: false }); |
以上代码创建了一个基础的 VueQuillEditor
组件,我们可以在其中输入和编辑文本。
3. 自定义内容的插入
接下来,我们会在 Quill 编辑器中插入自定义内容,比如一个带特定样式的 span
标签。为此,我们需要创建一个 Quill 的自定义 Blot 元素。
- 新建
CustomSpanBlot.ts
文件
在 src/quill-blots
文件夹下新建 CustomSpanBlot.ts
文件,用于定义我们自定义的 span
标签格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import { Quill } from '@vueup/vue-quill' ; const Inline = Quill. import ( "blots/inline" ); class CustomSpanBlot extends Inline { static blotName = "customSpan" ; static tagName = "span" ; static className = "custom-span" ; static create(value: string) { const node = super .create(); node.setAttribute( "data-custom" , value); node.innerHTML = value; return node; } static formats(node: HTMLElement) { return node.getAttribute( "data-custom" ); } format(name: string, value: string) { if (name === CustomSpanBlot.blotName && value) { this .domNode.setAttribute( "data-custom" , value); this .domNode.innerHTML = value; } else { super .format(name, value); } } } export { CustomSpanBlot }; |
4. 插入内容到编辑器
在 QuillEditor.vue
中引入自定义的 CustomSpanBlot
,并编写插入自定义内容的方法:
1 2 3 4 5 6 7 8 9 10 | import { CustomSpanBlot } from './CustomSpanBlot' ; // 进行注册 Quill.register(CustomSpanBlot); // 初始化 onMounted(() => { // 新增自定义功能 const newFunctionButton = document.querySelector( '.ql-newFunction' ); newFunctionButton.setAttribute( 'style' , 'width:80px; border:1px solid #ccc; border-radius:5px' ); newFunctionButton.textContent = '新功能' ; }); |
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。