富文本编辑器 vue-quill-editor 实现 mention 提醒功能

业务需要要实现一个富文本编辑器,而且同时还要实现提醒@的功能。

组件官网地址:1. https://www.npmjs.com/package/@yixink/quill-mention

2. https://github.surmon.me/vue-quill-editor/

1.组件准备

使用vue-quill-editor 和 quill-mention 实现此功能

安装组件

yarn add quill  vue-quill-editor quill-mention -D

2.组件引入 

在main.js 引入组件

import VueQuillEditor from 'vue-quill-editor' //引入富文本编译器

import 'quill/dist/quill.core.css'

import 'quill/dist/quill.snow.css'

import 'quill/dist/quill.bubble.css'

Vue.use(VueQuillEditor)

3.页面引入编辑器

在所需要使用编辑器的页面引入编辑器

1) 在script 引入文件

import Quill from 'quill'

import { quillEditor } from 'vue-quill-editor' // 引入富文本

import mention from 'quill-mention' // 引入mention 组件

import 'quill-mention/dist/quill.mention.min.css'

// 为quill 注册mention 组件

Quill.register({

'modules/mention': mention,

})

2)准备配置项(在data里面定义)

editorOptions: {

placeholder: this.placeholder, // 文本提示信息

modules: { 

toolbar: [['bold', 'underline', { color: [] }, { list: 'ordered' }, { list: 'bullet' }]], // 定义菜单栏 (粗体,下划线,颜色,排序。其他配置的可以到官网去找)

mention: {  // 重点: 提醒功能配置项

allowedChars: /^[A-Za-z\s]*$/, // 正则匹配

mentionDenotationChars: ['@'], // 匹配符号,匹配到@符号弹出提醒框

offsetLeft: 4,

source: (searchTerm, renderList, mentionChar) => { // 数据源(遍历成{id, value}形式)

const values = that.$store.getters.userList.map(item => ({

id: item.value,

value: item.key,

}))

renderList(values, searchTerm) // 渲染函数(生成提醒框)

},

onSelect:(data, insertItem) => { // 注意:选中后的回调函数

const item = {

text: `@${data.value}`,

name: data.value,

id: data.id,

}

insertItem(data) // 注意:这个函数必须加上,有这个才会在文本框显示选中的值

this.onSelectd(item) // 返回给后端的选中提醒的人

},

},

},

},

扩展:toolbar 配置

// [{ 'font': [] }],  字体

// ['bold', 'underline'], 下划线和粗体

// [{ 'header': 1 }, { 'header': 2 }], 标题

// [{ 'script': 'sub' }, { 'script': 'super' }], 上下标

// [{ indent: '-1' }, { indent: '+1' }], 缩进

// [{ 'size': ['small', false, 'large', 'huge'] }], 字体大小

// [{ header: [1, 2, 3, 4, 5, 6, false] }], 标题

// [{ align: [] }], 对齐

// ['blockquote', 'code-block'], 块引入,代码段

// ['image'], // 链接、图片、视频

3.页面使用富文本框

<quill-editor
    v-model="value"
    :options="editorOptions"
    @change="onHandleChange" // 文本改变回调函数
/>

4. 效果如下

 

5.优点

解决了很多使用文本框又使用提醒功能的时候会出现光标异常的问题

猜你喜欢

转载自blog.csdn.net/qq_25687271/article/details/115184228
今日推荐