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

Vue.js任务完成按钮页面刷新后状态重置问题求助

Got it, let's fix that frustrating issue where your task completion button resets after a page refresh! The root problem here is that right now, you're only storing the task status in Vue's reactive data—which lives in the browser's temporary memory. When you refresh, that memory gets wiped clean, so the button reverts to its initial state. Let's break down the fixes step by step:

1. First: Sync Your Backend & Frontend State

Right now, you're toggling the status locally in Vue after the API call, but we should trust the backend to return the definitive updated state. This ensures consistency between what's stored in your database and what the user sees.

Update Your Laravel Controller

Make sure your /follow/{taskId} endpoint returns the actual updated status after modifying the database:

public function follow($taskId)
{
    $task = Task::findOrFail($taskId);
    // Toggle the task's completed status for the authenticated user
    auth()->user()->tasks()->toggle($taskId);
    
    // Return the fresh status to the frontend
    $isCompleted = auth()->user()->tasks()->where('task_id', $taskId)->exists();
    return response()->json(['status' => $isCompleted]);
}

Update Your Vue Method

Replace the local toggle with the backend's returned status to avoid mismatches:

followUser() {
    axios.post('/follow/' + this.taskId)
        .then(response => {
            this.status = response.data.status; // Use backend's definitive status
            console.log(response.data);
        })
        .catch(errors => {
            if (errors.response.status == 401) {
                window.location = '/login';
            }
        });
}

2. Persist State Locally (For Instant Refresh Recovery)

Even with backend sync, page reloads will still wait for the initial page load to get the status. To make the button state load instantly, we can save the status to localStorage (browser persistent storage).

Modified Vue Component Code

<template>
    <div>
        <button class="btn btn-primary ml-4" @click="followUser" v-text="buttonText"></button>
    </div>
</template>

<script>
export default {
    props: ['taskId', 'follows'],
    mounted() {
        // On page load: pull saved status from localStorage if it exists
        const savedStatus = localStorage.getItem(`task_${this.taskId}_status`);
        if (savedStatus !== null) {
            this.status = JSON.parse(savedStatus);
        } else {
            // Fallback to the initial prop value from the backend
            this.status = this.follows;
        }
        console.log('Component mounted.');
    },
    data: function () {
        return {
            status: false, // Initial placeholder, overwritten in mounted
        };
    },
    watch: {
        // Auto-save status to localStorage whenever it changes
        status(newStatus) {
            localStorage.setItem(`task_${this.taskId}_status`, JSON.stringify(newStatus));
        }
    },
    methods: {
        followUser() {
            axios.post('/follow/' + this.taskId)
                .then(response => {
                    this.status = response.data.status;
                    console.log(response.data);
                })
                .catch(errors => {
                    if (errors.response.status == 401) {
                        window.location = '/login';
                    }
                });
        }
    },
    computed: {
        buttonText() {
            return this.status ? 'completed' : 'complete';
        }
    }
};
</script>

3. Double-Check Initial Prop Value

Make sure your Blade template passes the latest database status to the Vue component when the page first loads:

<task-button 
    :task-id="{{ $task->id }}" 
    :follows="{{ auth()->user()->tasks()->where('task_id', $task->id)->exists() ? 'true' : 'false' }}"
></task-button>

What This Does

  • The backend always acts as the single source of truth for task status
  • localStorage keeps the status alive between page refreshes, so the button updates instantly without waiting for a backend call
  • On initial load, we prioritize the saved local state (for speed) but fall back to the backend's value if no local state exists

内容的提问来源于stack exchange,提问作者jsmith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:22:48