返回
Vue+wangEditor v5实现@ mention功能
前端
2023-10-08 17:50:54
WangEditor V5 即将发布,为了验证它的可扩展性,我最近制作了几个第三方插件。可以查看插件列表。本文分享 @ mention 插件的设计和实现,以 Vue 为例,源代码在本文末尾。
前言
在编辑器中,通常需要实现@功能,即当用户输入"@"时,会弹出一个下拉框,列出所有可以被@的人员。本文将分享如何使用Vue+wangEditor v5实现@ mention功能,并提供代码示例。
实现步骤
1. 安装依赖
首先,我们需要安装wangEditor v5和Vue。
npm install wangEditor v5
npm install vue
2. 创建Vue组件
接下来,我们需要创建一个Vue组件,用于实现@ mention功能。
<template>
<div>
<wang-editor ref="editor" :config="config" v-model="content"></wang-editor>
</div>
</template>
<script>
import { WangEditor } from 'wangEditor'
import '@wangeditor/mention'
export default {
data() {
return {
content: '',
config: {
menuConfig: {
mention: {
// 配置 mention 功能
mentionList: [
{
name: '张三',
id: 'zhangsan'
},
{
name: '李四',
id: 'lisi'
}
],
// 触发 @ mention 功能的字符
mentionChar: '@'
}
}
}
}
},
mounted() {
// 创建编辑器实例
const editor = new WangEditor(this.$refs.editor)
// 启动编辑器
editor.create()
}
}
</script>
3. 注册组件
最后,我们需要将组件注册到Vue实例中。
import MyComponent from './MyComponent.vue'
export default new Vue({
el: '#app',
components: {
MyComponent
}
})
效果预览
运行代码后,你将看到一个文本编辑器,在编辑器中输入"@"时,会弹出一个下拉框,列出所有可以被@的人员。
结语
本文分享了如何使用Vue+wangEditor v5实现@ mention功能。希望对大家有所帮助。
源码
<template>
<div>
<wang-editor ref="editor" :config="config" v-model="content"></wang-editor>
</div>
</template>
<script>
import { WangEditor } from 'wangEditor'
import '@wangeditor/mention'
export default {
data() {
return {
content: '',
config: {
menuConfig: {
mention: {
// 配置 mention 功能
mentionList: [
{
name: '张三',
id: 'zhangsan'
},
{
name: '李四',
id: 'lisi'
}
],
// 触发 @ mention 功能的字符
mentionChar: '@'
}
}
}
}
},
mounted() {
// 创建编辑器实例
const editor = new WangEditor(this.$refs.editor)
// 启动编辑器
editor.create()
}
}
</script>