使用插件quill-mention,实现在quill 富文本编辑器使用@或#提及用户。
1. 安装
npm install quill-mention --save
2. 官方给的示例quill-mention
import "quill-mention";
const atValues = [
{ id: 1, value: "Fredrik Sundqvist" },
{ id: 2, value: "Patrik Sjölin" }
];
const hashValues = [
{ id: 3, value: "Fredrik Sundqvist 2" },
{ id: 4, value: "Patrik Sjölin 2" }
];
const quill = new Quill("#editor", {
modules: {
mention: {
allowedChars: /^[A-Za-z0-9_]*$/,
mentionDenotationChars: ["@", "#"],
source: function(searchTerm, renderList, mentionChar) {
let values;
if (mentionChar === "@") {
values = atValues;
} else {
values = hashValues;
}
if (searchTerm.length === 0) {
renderList(values, searchTerm);
} else {
const matches = [];
for (let i = 0; i < values.length; i++)
if (
~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())
)
matches.push(values[i]);
renderList(matches, searchTerm);
}
}
}
}
});
3. 在vue2中使用的示例,已省去无关代码。(示例来自自行封装的Quill.vue通用组件)
<template>
<quill-editor>...</quill-editor>
</template>
<script>
import { quillEditor, Quill } from 'vue-quill-editor'
import "quill-mention"
// 工具栏配置
const toolbarOptions = [...];
export default {
name: 'Quill',
components: { quillEditor },
props: {
// 提及的用户数据
atValues: {
typ: Object,
default: ()=>[]
},
hashValues: {
typ: Object,
default: ()=>[]
}
},
data() {
return {
editorOption: {
modules: {
mention: {
allowedChars: /^[a-zA-Z0-9_]*$/,
mentionDenotationChars: ["@", "#"],
source: (searchTerm, renderList, mentionChar) => {
let values
if (mentionChar === "@") {
values = this.atValues
} else {
values = this.hashValues
}
if (searchTerm.length === 0) {
renderList(values, searchTerm);
} else {
const matches = []
for (let i = 0; i < values.length; i++)
if (
~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase())
)
matches.push(values[i])
renderList(matches, searchTerm)
}
},
// 选中后触发
onSelect: (item, insertItem) => {
this.$emit('atUser', item.id)
insertItem(item)
}
}
}
}
}
}
}
</script>
<style lang="less" scoped></style>
4. 无论哪个示例,记得引入css样式。在源码的 dist/quill.mention.css
.ql-mention-list-container {
width: 270px;
border: 1px solid #f0f0f0;
border-radius: 4px;
background-color: #ffffff;
box-shadow: 0 2px 12px 0 rgba(30, 30, 30, 0.08);
z-index: 9001;
overflow: auto;
}
.ql-mention-loading {
line-height: 44px;
padding: 0 20px;
vertical-align: middle;
font-size: 16px;
}
.ql-mention-list {
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
}
.ql-mention-list-item {
cursor: pointer;
line-height: 44px;
font-size: 16px;
padding: 0 20px;
vertical-align: middle;
}
.ql-mention-list-item.disabled {
cursor: auto;
}
.ql-mention-list-item.selected {
background-color: #d3e1eb;
text-decoration: none;
}
.mention {
height: 24px;
width: 65px;
border-radius: 6px;
background-color: #d3e1eb;
padding: 3px 0;
margin-right: 2px;
user-select: all;
}
.mention > span {
margin: 0 3px;
}
5. 效果