vue的艾特功能实现
Vue 中实现 @ 提及功能
在 Vue 中实现 @ 提及功能通常需要结合文本输入框、事件监听和用户列表展示。以下是实现步骤:
1. 监听输入框内容变化
使用 v-model 绑定输入框内容,并监听输入事件。当用户输入 @ 时,触发用户列表显示。
<template>
<div>
<textarea v-model="content" @input="handleInput"></textarea>
<div v-if="showUserList">
<ul>
<li v-for="user in filteredUsers" @click="selectUser(user)">
{{ user.name }}
</li>
</ul>
</div>
</div>
</template>
2. 检测 @ 符号并过滤用户列表

在 handleInput 方法中检测 @ 符号,并根据输入内容过滤用户列表。
<script>
export default {
data() {
return {
content: '',
showUserList: false,
users: [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
],
filteredUsers: [],
};
},
methods: {
handleInput() {
const cursorPos = this.$refs.textarea.selectionStart;
const textBeforeCursor = this.content.substring(0, cursorPos);
const atIndex = textBeforeCursor.lastIndexOf('@');
if (atIndex !== -1) {
const query = textBeforeCursor.substring(atIndex + 1);
this.filteredUsers = this.users.filter(user =>
user.name.includes(query)
);
this.showUserList = this.filteredUsers.length > 0;
} else {
this.showUserList = false;
}
},
selectUser(user) {
const cursorPos = this.$refs.textarea.selectionStart;
const textBeforeCursor = this.content.substring(0, cursorPos);
const atIndex = textBeforeCursor.lastIndexOf('@');
this.content =
this.content.substring(0, atIndex) +
`@${user.name}` +
this.content.substring(cursorPos);
this.showUserList = false;
},
},
};
</script>
3. 添加样式和优化体验

为下拉列表添加样式,并在点击外部时关闭列表。
<style>
ul {
list-style: none;
padding: 0;
margin: 0;
border: 1px solid #ccc;
max-height: 150px;
overflow-y: auto;
}
li {
padding: 5px 10px;
cursor: pointer;
}
li:hover {
background-color: #f0f0f0;
}
</style>
4. 处理多行文本和复杂场景
如果需要支持多行文本或更复杂的场景,可以使用第三方库如 tributejs 或 mention-vue。以下是使用 mention-vue 的示例:
import Vue from 'vue';
import Mentionable from 'mention-vue';
import 'mention-vue/dist/mention-vue.css';
Vue.use(Mentionable);
<template>
<mentionable
:items="users"
:insert-space="false"
@open="onOpen"
@search="onSearch"
@close="onClose"
>
<textarea v-model="content"></textarea>
</mentionable>
</template>
通过以上方法,可以在 Vue 中实现基本的 @ 提及功能。根据项目需求,可以选择原生实现或使用现有库简化开发。






