You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js+Laravel关注/取消关注系统:v-for循环切换与数据插入问题求助

Vue.js + Laravel 关注/取消关注系统修复方案

问题现状

使用Vue.js结合Laravel构建关注系统时,遇到两个核心问题:

  • v-for循环渲染用户列表时,无法为单个用户独立切换关注/取消关注图标
  • 关注操作的数据插入逻辑存在问题,且未实现取消关注功能

现有代码问题分析

  1. 模板判断错误:图标切换逻辑用user作为判断条件,永远为真,导致图标无法切换
  2. 状态管理混乱:使用全局this.user存储单个用户ID,无法区分列表中不同用户的关注状态
  3. 逻辑语法错误:toggleFollow里的if (this.user = !this.user)是赋值操作而非判断,逻辑完全错误
  4. 后端方法问题:store方法使用insert批量插入语法,但实际是创建单条记录,且未处理取消关注的逻辑

修复步骤与完整代码

1. 前端Vue组件修复

模板部分

修改图标切换逻辑,根据用户的is_followed状态决定显示的图标:

<template>
<ul class="suggestions-lists m-0 p-0">
    <li v-for="(user, index) in users" :key="user.id" class="d-flex mb-4 align-items-center">
            <h6>{{user.name}}</h6>
        <div class="add-suggestion">
            <a href="javascript:void(0);" @click="toggleFollow(user)">
                <i :class="'text-danger ' + (user.is_followed ? 'ri-user-follow-line' : 'ri-user-add-line')"></i>
            </a>
        </div>
    </li>
</ul>
</template>

脚本部分

添加已关注用户状态标记,重构关注/取消逻辑,修复状态更新:

<script>
export default {
props: ['userid'],
data: function () {
    return {
        users: [] 
    }
},

methods: {
    getUsers: async function() {
        try {
            // 获取用户列表
            const userRes = await axios.get('/followers');
            // 获取当前用户已关注的列表
            const followedRes = await axios.get('/followers/following');
            const followedIds = followedRes.data.map(item => item.following_id);
            
            // 为每个用户添加关注状态标记
            this.users = userRes.data.map(user => ({
                ...user,
                is_followed: followedIds.includes(user.id)
            }));
        } catch (error) {
            console.log(error.message);
        }
    },
    toggleFollow: async function (user) {
        if (user.is_followed) {
            await this.followRemove(user);
        } else {
            await this.followAdd(user);
        }
        // 切换本地状态,无需重新请求列表
        user.is_followed = !user.is_followed;
    },          
    followAdd: async function (user) {
        try {
            await axios.post('/followers/store', { 
                follower: this.userid, 
                following: user.id 
            });
        } catch (errors) {
            console.log(errors);
            // 失败时回滚状态
            user.is_followed = false;
        }
    },
    followRemove: async function (user) {
        try {
            await axios.delete('/followers/destroy', {
                data: {
                    follower: this.userid,
                    following: user.id
                }
            });
        } catch (errors) {
            console.log(errors);
            // 失败时回滚状态
            user.is_followed = true;
        }
    }
},

created() {
  this.getUsers();
},
}
</script>

2. Laravel后端修复

路由添加

在routes/api.php中添加对应路由:

Route::get('/followers', [FollowersController::class, 'index']);
Route::get('/followers/following', [FollowersController::class, 'getFollowing']);
Route::post('/followers/store', [FollowersController::class, 'store']);
Route::delete('/followers/destroy', [FollowersController::class, 'destroy']);

Controller方法调整

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Followers;

class FollowersController extends Controller
{
    // 获取可关注的用户列表
    public function index()
    {
        // 根据实际需求排除当前用户,示例返回所有用户
        return response()->json(Followers::all());
    }

    // 获取当前用户已关注的列表
    public function getFollowing(Request $request)
    {
        return response()->json(Followers::where('follower_id', $request->user()->id)->get());
    }

    // 关注用户
    public function store(Request $request)
    {
        $request->validate([
            'follower' => 'required|integer',
            'following' => 'required|integer|different:follower'
        ]);

        // 避免重复关注
        $follow = Followers::firstOrCreate([
            'follower_id' => $request->follower,
            'following_id' => $request->following
        ]);

        return response()->json($follow, 201);
    }

    // 取消关注用户
    public function destroy(Request $request)
    {
        $deleted = Followers::where([
            'follower_id' => $request->follower,
            'following_id' => $request->following
        ])->delete();

        return response()->json(['success' => $deleted > 0], 200);
    }
}

关键说明

  • 通过is_followed字段为每个用户独立维护关注状态,实现图标独立切换
  • 关注/取消操作后直接更新本地状态,提升用户体验,无需重新请求整个列表
  • 后端使用firstOrCreate避免重复关注,添加参数验证确保数据合法性
  • 失败时回滚前端状态,避免界面与实际数据不一致

内容的提问来源于stack exchange,提问作者RK-Rohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:30:57