vue3使用vuequill插入自定义按钮
在 vue 3 项目中使用 vuequill
编辑器时,我们可以自定义内容来满足特定的需求。
本文将介绍如何在 vuequill
中插入自定义内容,比如插入特定的标签或样式元素。
1. 项目设置和依赖安装
如果你还没有创建 vue 3 项目,可以使用以下命令来初始化项目:
npm init vue@latest
选择 vue 3 的相关配置,然后进入项目目录并安装依赖项。
安装 vuequill
npm install @vueup/vue-quill
此库是 quill 编辑器的 vue 3 兼容版本。
2. 基础配置 vuequill
在 src/components
中创建一个 quilleditor.vue
文件,并引入 vue3-quill
,将 vuequilleditor
作为编辑器组件使用。
template
内容
<template> <div class="editor"> <quill-editor ref="quilleditorref" v-model:content="content" content-type="html" :options="options" :style="styles" @text-change="textchangefn" /> </div> </template>
options
内容:
import '@vueup/vue-quill/dist/vue-quill.snow.css'; import { quill } from '@vueup/vue-quill'; const options = ref<any>({ 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
标签格式:
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
,并编写插入自定义内容的方法:
<script lang="ts"> 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 = '新功能'; }); </script>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论