当前位置:首页 > VUE

vue实现好友列表

2026-01-07 01:49:22VUE

实现好友列表的Vue组件

数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。

data() {
  return {
    friends: [
      { id: 1, name: '张三', avatar: '/avatars/1.jpg', status: 'online' },
      { id: 2, name: '李四', avatar: '/avatars/2.jpg', status: 'offline' },
      { id: 3, name: '王五', avatar: '/avatars/3.jpg', status: 'online' }
    ]
  }
}

模板结构 使用v-for指令循环渲染好友列表,结合条件渲染显示不同状态的好友。

<template>
  <div class="friend-list">
    <div v-for="friend in friends" :key="friend.id" class="friend-item">
      <img :src="friend.avatar" class="avatar">
      <span class="name">{{ friend.name }}</span>
      <span class="status" :class="friend.status">{{ friend.status }}</span>
    </div>
  </div>
</template>

样式设计 为好友列表添加CSS样式,增强视觉效果。

vue实现好友列表

.friend-list {
  width: 300px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.status {
  margin-left: auto;
  font-size: 12px;
  color: #999;
}

.status.online {
  color: #67C23A;
}

.status.offline {
  color: #909399;
}

交互功能 添加点击事件处理,实现好友选择功能。

methods: {
  selectFriend(friend) {
    this.$emit('friend-selected', friend)
  }
}

在模板中绑定点击事件:

vue实现好友列表

<div v-for="friend in friends" 
     :key="friend.id" 
     class="friend-item"
     @click="selectFriend(friend)">

数据加载 实际项目中通常需要从API获取好友数据。

created() {
  this.fetchFriends()
},
methods: {
  async fetchFriends() {
    try {
      const response = await axios.get('/api/friends')
      this.friends = response.data
    } catch (error) {
      console.error('获取好友列表失败', error)
    }
  }
}

状态管理 对于大型应用,建议使用Vuex管理好友状态。

computed: {
  friends() {
    return this.$store.state.friends.list
  }
}

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

相关文章

vue实现图片

vue实现图片

Vue 实现图片功能的方法 静态图片引入 在 Vue 项目中,可以通过 src 属性直接引入静态图片。图片通常放在 public 或 assets 目录下。 <template> &…

vue 实现modal

vue 实现modal

Vue 实现 Modal 的方法 使用 Vue 原生组件 通过 Vue 的组件系统可以轻松实现 Modal。创建一个可复用的 Modal 组件,通过 props 控制显示与隐藏。 <templ…

vue 菜单实现

vue 菜单实现

Vue 菜单实现方法 在Vue中实现菜单功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for动态生成菜单 通过数据驱动的方式动态渲染菜单项,适合菜单内容可能变化的场景: <t…

vue 实现上传

vue 实现上传

Vue 实现文件上传 使用 Vue 实现文件上传可以通过原生 HTML 的 <input type="file"> 或第三方库(如 axios、vue-upload-component)完…

vue实现拖拉

vue实现拖拉

实现拖拽功能的基本步骤 在Vue中实现拖拽功能可以通过原生HTML5的拖放API或第三方库如vuedraggable完成。以下是两种方法的详细说明。 使用HTML5原生拖放API HTML5提供了原…

vue实现追加

vue实现追加

追加数据到数组或列表 在Vue中追加数据到数组或列表,可以通过push方法或concat方法实现。以下是几种常见的实现方式: 方法一:使用push方法 this.items.push(newIte…