How to use Vue to implement the add friend function

PHPz
Release: 2023-04-12 10:15:17
Original
975 people have browsed it

With the rise of social media, adding friends has become an indispensable part of people's daily interactions. For front-end developers, how to implement the function of adding friends on the page is a question worth thinking about. This article will introduce how to use the Vue framework to implement the add friend function.

1. Prerequisite knowledge

Before we start introducing the friend adding function, we need to know the following:

  1. Use Vue CLI to create a project;
  2. Basic concepts and usage of Vue components;
  3. Methods for passing values ​​between parent and child components;
  4. Basic concepts and usage of Vue Router.

2. Design page

When designing the page for adding friends, we need to consider the layout and functionality of the page. Usually, the adding friend function needs to include the following content:

  1. Search box: users can enter the friend’s name or ID in the search box to search;
  2. User list: based on the search results Display the user list;
  3. Add friend button: Users can click the add friend button to send friend requests to users in the search results.

Based on the above content, we can design the following page layout:

<template>
  <div class="friend-add">
    <!-- 搜索框部分 -->
    <div class="search-bar">
      <input type="text" placeholder="请输入好友名字或ID" v-model="keyword">
      <button @click="search">搜索</button>
    </div>
    <!-- 用户列表部分 -->
    <div class="user-list">
      <ul>
        <li v-for="(user, index) in userList" :key="index">
          {{ user.name }}
          <button @click="addFriend(user)">添加好友</button>
        </li>
      </ul>
    </div>
  </div>
</template>
Copy after login

3. Implement the function

After designing the page layout, we need to implement the function of adding friends Function. The following is the specific implementation method:

  1. Get the user list

After the user enters the keyword in the search box, we need to request through the interface to obtain the user list that meets the search conditions user list. In Vue, we usually encapsulate this function into a component:

<template>
  <div class="user-list">
    <ul>
      <li v-for="(user, index) in userList" :key="index">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        userList: []
      }
    },
    methods: {
      getUserList() {
        // TODO: 发送接口请求,获取用户列表
        this.userList = [
          { name: '张三', id: 1 },
          { name: '李四', id: 2 },
          { name: '王五', id: 3 },
        ]
      }
    },
    mounted() {
      this.getUserList()
    }
  }
</script>
Copy after login

In the above code, we define a method named getUserList, which is used to send requests to the backend to obtain the items that match the search conditions. User list, in the mounted function, we call the getUserList method, so that after the component is loaded, a request will be sent to the backend to obtain the user list.

  1. Passing values ​​between parent and child components

In Vue, parent components pass data to child components, which can be achieved through props. We can pass the keywords entered by the user in the search box to the subcomponent through props, so that the subcomponent can search based on the search keywords when sending a request.

<template>
  <div class="friend-add">
    <div class="search-bar">
      <!-- 在搜索框中添加v-model指令,将输入框中的值与父组件的keyword进行双向绑定 -->
      <input type="text" placeholder="请输入好友名字或ID" v-model="keyword">
      <button @click="search">搜索</button>
    </div>
    <user-list :keyword="keyword"></user-list>
  </div>
</template>

<script>
  import UserList from './UserList'
  
  export default {
    components: {
      UserList
    },
    data() {
      return {
        keyword: ''
      }
    },
    methods: {
      search() {
        // 点击搜索按钮时触发该函数,这里的search功能可以自行实现
        this.$refs.userList.getUserList()
      }
    }
  }
</script>
Copy after login

In the above code, we define a data attribute named keyword to store the keywords entered by the user in the search box. In addition, we also introduced a component named UserList, using props to pass keywords to the subcomponent, and when the search button is clicked, the getUserList method of the subcomponent is called to trigger the search function.

In the child component, we need to first define a props named keyword:

<template>
  <div class="user-list">
    <ul>
      <li v-for="(user, index) in userList" :key="index">
        {{ user.name }}
        <button @click="addFriend(user)">添加好友</button>
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    props: {
      keyword: String
    },
    data() {
      return {
        userList: []
      }
    },
    methods: {
      getUserList() {
        // TODO:根据this.keyword向后端发送请求,获取用户列表
      },
      addFriend(user) {
        // TODO:向后端发送请求,添加好友
      }
    }
  }
</script>
Copy after login

In the above code, we define a props named keyword to receive the props passed by the parent component Come over to the value. In the getUserList method, we can use this.keyword to get the keywords passed by the parent component for search. The addFriend method is used to send requests to the backend to add friends.

  1. Vue Router

When implementing the friend adding function, we usually need to consider the page jump problem after the user adds a friend. In order to better implement the page jump function, we need to use Vue Router.

First of all, when creating a Vue project, you need to choose to use Vue Router:

vue create my-project
Copy after login

When selecting Options, select Manually select features, then select Router, and install it.

Next, after successfully adding friends, we need to jump to the add friend details page. This function can be implemented using Vue Router:

<template>
  <div>
    <!-- 用户列表部分 -->
    <div class="user-list">
      <ul>
        <li v-for="(user, index) in userList" :key="index">
          {{ user.name }}
          <button @click="addFriend(user)">添加好友</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  
  export default {
    data() {
      return {
        userList: []
      }
    },
    computed: {
      ...mapState(['userInfo'])
    },
    methods: {
      async addFriend(user) {
        // 向后端发送请求,添加好友
        await this.$http.post('/add-friend', {id: user.id})
        
        // 添加好友成功之后,跳转到好友详情页面
        this.$router.push({ name: 'friendDetail', params: { friendId: user.id } })
      }
    }
  }
</script>
Copy after login

In the above code, we first introduced Vuex’s mapState function to obtain user information through this function. Then, in the addFriend method, we send a request to the backend to add a friend. After the friend is added successfully, we use Vue Router to jump to the friend details page. When jumping, we use the name and params attributes of the route. The name attribute represents the name of the page, and the params attribute represents the passed parameters. We can define the route in src/router/index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import FriendDetail from '@/views/FriendDetail.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/friend-detail/:friendId',
    name: 'friendDetail',
    component: FriendDetail
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
Copy after login

In the above code, we define a route named friendDetail. The path attribute of the route represents the path to access the page, name The attribute represents the name of the route, and the component attribute represents the component corresponding to the route. The FriendDetail component is a component used to display friend details pages. In this component, friend information can be obtained based on the passed friendId.

4. Conclusion

In this article, we introduced how to use the Vue framework to implement the friend adding function. Through the implementation of this function, we can not only expand our front-end skills, but also improve our communication and social skills and establish more social relationships through this function.

The above is the detailed content of How to use Vue to implement the add friend function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!