如何获取Quill Mention选中的提及对象?基于ngx-quill的技术问询
问题描述
我在使用ngx-quill集成Quill Mention时,文本编辑和格式设置功能均正常,但找不到Quill Mention列表的onSelect事件。我的最终需求是将下拉列表中选中的提及对象存入数组,目前仅能使用mention-clicked和hover这两个与提及元素相关的事件监听器,请问如何获取选中的提及对象?
现有代码
HTML代码:
<quill-editor [modules]="{ mention: mentionConfig }" [style]="{height: '300px'}"></quill-editor>
Angular TS导入:
import Quill from 'quill'; import 'quill-mention'; import { QuillEditorComponent } from 'ngx-quill';
TS/JS代码:
@ViewChild(QuillEditorComponent) editor!: QuillEditorComponent; mentionConfig = { allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/, mentionDenotationChars: ["@"], "toolbar":false, source: (searchTerm: string, renderList:any) => { const values = [ { id: 1, value: 'Alice' }, { id: 2, value: 'Bob' }, { id: 3, value: 'Charlie' }, ]; const matches = values.filter(mention => mention.value.toLowerCase().includes(searchTerm.toLowerCase())); renderList(matches, searchTerm); } };
解决方案
你可以通过两种方式获取选中的提及对象:
方法1:在mention配置中添加onSelect回调
Quill Mention原生支持在配置里定义onSelect函数,选中列表项时会直接触发该回调并返回选中的对象。修改你的mentionConfig即可:
// 先定义存储选中对象的数组 selectedMentions: any[] = []; mentionConfig = { allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/, mentionDenotationChars: ["@"], toolbar: false, source: (searchTerm: string, renderList: any) => { const values = [ { id: 1, value: 'Alice' }, { id: 2, value: 'Bob' }, { id: 3, value: 'Charlie' }, ]; const matches = values.filter(mention => mention.value.toLowerCase().includes(searchTerm.toLowerCase())); renderList(matches, searchTerm); }, // 添加onSelect回调 onSelect: (item: any, insertItem: Function) => { // 直接拿到选中的提及对象 console.log('选中的对象:', item); // 存入目标数组 this.selectedMentions.push(item); // 必须调用insertItem,否则选中的内容不会插入到编辑器中 insertItem(item); } };
方法2:监听mention-clicked事件
如果更倾向于使用已有的事件监听器,可以在模板中绑定mention-clicked事件,从事件参数中提取选中对象:
修改HTML模板:
<quill-editor [modules]="{ mention: mentionConfig }" [style]="{height: '300px'}" (mention-clicked)="handleMentionClick($event)" ></quill-editor>
在TS中实现事件处理函数:
selectedMentions: any[] = []; handleMentionClick(event: any) { // 从event参数中取出选中的对象 const selectedItem = event.item; console.log('选中的对象:', selectedItem); this.selectedMentions.push(selectedItem); }
两种方法都能满足需求,推荐第一种,因为是Quill Mention官方提供的回调逻辑,更贴合插件设计。
内容的提问来源于stack exchange,提问作者akhilkrishnan1268
相关产品推荐
相关产品推荐

