当前位置:首页 > VUE

vue实现选择好友群发

2026-02-24 09:26:49VUE

Vue 实现选择好友群发功能

数据准备

在 Vue 的 datasetup 中定义好友列表和选中好友的数组:

data() {
  return {
    friends: [
      { id: 1, name: '张三', selected: false },
      { id: 2, name: '李四', selected: false }
    ],
    selectedFriends: []
  }
}

好友选择界面

使用 v-for 渲染好友列表,并通过 v-model 绑定选择状态:

<div v-for="friend in friends" :key="friend.id">
  <input 
    type="checkbox" 
    v-model="friend.selected"
    @change="updateSelectedFriends(friend)"
  >
  <label>{{ friend.name }}</label>
</div>

更新选中好友

在 methods 中定义方法处理选中状态变化:

vue实现选择好友群发

methods: {
  updateSelectedFriends(friend) {
    if (friend.selected) {
      this.selectedFriends.push(friend.id)
    } else {
      const index = this.selectedFriends.indexOf(friend.id)
      this.selectedFriends.splice(index, 1)
    }
  }
}

群发消息功能

添加消息输入框和发送按钮:

<textarea v-model="message" placeholder="输入要发送的消息"></textarea>
<button @click="sendBatchMessages" :disabled="selectedFriends.length === 0">
  群发消息
</button>

发送逻辑实现

实现群发消息的核心方法:

vue实现选择好友群发

methods: {
  sendBatchMessages() {
    if (this.selectedFriends.length === 0) return

    this.selectedFriends.forEach(friendId => {
      const friend = this.friends.find(f => f.id === friendId)
      console.log(`发送给 ${friend.name}: ${this.message}`)
      // 这里替换为实际的API调用
    })

    // 清空选择
    this.friends.forEach(f => f.selected = false)
    this.selectedFriends = []
    this.message = ''
  }
}

优化体验

添加全选/取消全选功能:

<button @click="toggleSelectAll">
  {{ allSelected ? '取消全选' : '全选' }}
</button>
computed: {
  allSelected() {
    return this.friends.every(f => f.selected)
  }
},
methods: {
  toggleSelectAll() {
    const select = !this.allSelected
    this.friends.forEach(f => {
      f.selected = select
      this.updateSelectedFriends(f)
    })
  }
}

样式美化

使用 CSS 美化界面:

.friend-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
}
.friend-item:hover {
  background-color: #f5f5f5;
}

注意事项

  1. 实际项目中应将好友数据通过 API 从后端获取
  2. 群发消息需要调用后端接口批量处理
  3. 添加加载状态和错误处理提升用户体验
  4. 对于大量好友应考虑分页或虚拟滚动优化性能

标签: 好友vue
分享给朋友:

相关文章

vue全选实现

vue全选实现

Vue 全选实现方法 在 Vue 中实现全选功能通常涉及数据绑定和事件处理。以下是几种常见的实现方式: 基础实现方式 <template> <div> <…

vue 实现pc

vue 实现pc

Vue 实现 PC 端应用的核心要点 Vue.js 是一个渐进式框架,适合构建 PC 端单页应用(SPA)或复杂的前端界面。以下是实现 PC 端应用的关键方法和注意事项: 项目初始化与工程化配置 使…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安装…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…

vue实现编辑

vue实现编辑

Vue 实现编辑功能 在 Vue 中实现编辑功能通常涉及表单绑定、状态管理和事件处理。以下是一个常见的实现方法: 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定: <i…

vue实现定位打卡

vue实现定位打卡

Vue 实现定位打卡功能 获取用户地理位置 使用浏览器提供的 Geolocation API 获取用户当前位置坐标。在 Vue 组件中可以通过 navigator.geolocation 调用。 m…