当前位置:首页 > VUE

vue的艾特功能实现

2026-01-07 05:03:06VUE

Vue 的 @ 功能实现

在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法:

监听输入框内容

使用 v-model 绑定输入框内容,并通过 @input@keyup 监听输入变化。当检测到 @ 符号时,触发用户匹配逻辑。

<template>
  <textarea v-model="content" @input="handleInput"></textarea>
  <div v-if="showUserList">
    <div v-for="user in filteredUsers" @click="selectUser(user)">
      {{ user.name }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      content: '',
      showUserList: false,
      users: [], // 用户列表数据
      filteredUsers: [] // 匹配到的用户
    };
  },
  methods: {
    handleInput() {
      const lastAtPos = this.content.lastIndexOf('@');
      if (lastAtPos >= 0) {
        const query = this.content.slice(lastAtPos + 1);
        this.filteredUsers = this.users.filter(user => 
          user.name.includes(query)
        );
        this.showUserList = this.filteredUsers.length > 0;
      } else {
        this.showUserList = false;
      }
    },
    selectUser(user) {
      const lastAtPos = this.content.lastIndexOf('@');
      this.content = 
        this.content.slice(0, lastAtPos + 1) + 
        user.name + ' ';
      this.showUserList = false;
    }
  }
};
</script>

高亮显示 @ 用户

通过正则表达式匹配内容中的 @用户,并使用 <span> 标签包裹实现高亮。

methods: {
  formatContent(content) {
    return content.replace(/@(\w+)/g, '<span class="mention">@$1</span>');
  }
}
.mention {
  color: blue;
  font-weight: bold;
}

后端数据交互

将最终的输入内容(包含 @用户 信息)提交到后端,后端解析后通知被提及的用户。

methods: {
  submitContent() {
    axios.post('/api/submit', { content: this.content })
      .then(response => {
        console.log('提交成功');
      });
  }
}

使用现成库

如果需要快速实现,可以使用现成的 Vue 库如 vue-mention,简化开发流程。

安装:

npm install vue-mention

使用示例:

vue的艾特功能实现

<template>
  <vue-mention
    v-model="content"
    :items="users"
    item-text="name"
    @search="onSearch"
  />
</template>

通过以上方法,可以灵活实现 Vue 中的 @ 功能,满足社交平台或协作工具的需求。

标签: 功能vue
分享给朋友:

相关文章

vue 实现tabs

vue 实现tabs

Vue 实现 Tabs 组件的方法 使用动态组件和 v-for 在 Vue 中实现 Tabs 可以通过动态组件和 v-for 指令结合完成。定义一个 tabs 数组,包含每个标签的标题和对应的组件。…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue实现返回

vue实现返回

返回按钮功能实现 在Vue中实现返回功能通常有两种方式:使用浏览器历史记录的history.back()或结合Vue Router进行编程式导航。以下是具体实现方法: 使用浏览器API metho…

vue 实现筛选

vue 实现筛选

实现筛选功能的基本方法 在Vue中实现筛选功能通常涉及以下几个核心步骤: 数据绑定与筛选逻辑 使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选: data() {…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为 @…

vue实现groupbox

vue实现groupbox

Vue 实现 GroupBox 组件 在 Vue 中实现类似 GroupBox 的效果可以通过自定义组件完成。GroupBox 通常是一个带有标题的边框容器,用于将相关控件分组显示。 基本实现方法…