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

Vue.js登录错误弹窗提示实现求助(基于Vuex与Axios)

Solution for Login Status Code Handling & Token Storage

Got it, let's fix up your login flow step by step to handle those status codes correctly and get everything working as expected:

1. Clean Up the Template (HTML)

Your current template has duplicate error message renders and wonky v-show logic. Let's simplify it to display errors clearly without repetition:

<template>
  <form>
    <div class="login">
      <div>
        <input type="text" v-model="email" placeholder="Email" class="eSection" id="email">
        <input type="password" v-model="password" placeholder="Password" class="pSection" id="password">
        <!-- Centralized error message display -->
        <div class="error-container">
          <p v-for="(error, index) in errorM" :key="index" class="error-text">
            {{ error }}
          </p>
        </div>
        <button type="button" class="log" @click="login">LogIn</button>
      </div>
    </div>
  </form>
</template>

2. Refactor JavaScript Logic & Status Code Handling

We'll fix error message structure, correct status code checks, add Vuex token storage, and prevent error messages from piling up on repeated attempts:

<script>
import axios from 'axios';
// Uncomment if using Vuex mapActions for cleaner code
// import { mapActions } from 'vuex';

export default {
  data() {
    return {
      email: "test@gmail.com",
      password: "123456",
      errorM: [] // Holds current error messages
    };
  },
  // If using Vuex actions, uncomment this block
  // methods: {
  //   ...mapActions(['saveAuthToken']),
  //   login() { ... }
  // }
  methods: {
    login() {
      // Clear old errors before making a new request
      this.errorM = [];

      axios.post(`https://api.ticket.co/auth/login`, {
        email: this.email,
        password: this.password
      })
      .then(response => {
        console.log(response.data);
        console.log(response.status);
        
        // Handle 200: Store token in Vuex (with localStorage persistence)
        if (response.status === 200) {
          // Option 1: Direct Vuex commit (if store is accessible)
          this.$store.commit('SET_TOKEN', response.data.token);
          // Option 2: Use a Vuex action (better for async logic)
          // this.saveAuthToken(response.data.token);
          console.log("Token saved successfully:", response.data.token);
        }
      })
      .catch(e => {
        console.log(e);
        const status = e.response?.status;
        const vm = this;

        // Restructured error messages for easier access
        const errorMessages = {
          missingField: "Email/Password is missing. Please try again!",
          invalidEmail: "The email that has been entered is incorrect. Please try again!",
          invalidPassword: "The password that has been entered is incorrect. Please try again!",
          invalidCredentials: "Both Email and Password that have been entered are incorrect!"
        };

        switch (status) {
          case 400:
            // Check for missing fields first
            if (!vm.email || !vm.password) {
              vm.errorM.push(errorMessages.missingField);
            } else {
              // Add specific errors if fields are present but invalid
              if (!vm.email) vm.errorM.push(errorMessages.invalidEmail);
              if (!vm.password) vm.errorM.push(errorMessages.invalidPassword);
            }
            break;

          case 401:
            // Trigger when both fields are filled but incorrect
            if (vm.email && vm.password) {
              vm.errorM.push(errorMessages.invalidCredentials);
            }
            break;

          default:
            // Catch-all for unexpected errors
            vm.errorM.push("An unexpected error occurred. Please try again later.");
        }
      });
    }
  }
};
</script>

3. Vuex Store Setup for Token Management

Make sure your Vuex store has the necessary state, mutations, and actions to handle token storage (with persistence):

// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('authToken') || null // Persist token across page reloads
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem('authToken', token);
    },
    CLEAR_TOKEN(state) {
      state.token = null;
      localStorage.removeItem('authToken');
    }
  },
  actions: {
    saveAuthToken({ commit }, token) {
      commit('SET_TOKEN', token);
    }
  },
  getters: {
    isLoggedIn: state => !!state.token,
    getAuthToken: state => state.token
  }
});

Key Fixes & Improvements:

  • Simplified error rendering: Removed duplicate v-for blocks and centralized error display.
  • Better error message structure: Switched to an object instead of an array of single-property objects for easier access.
  • Error reset: Clears old errors on each login attempt to avoid message buildup.
  • Corrected 401 logic: Fixed the condition to trigger only when both fields are filled but incorrect.
  • Vuex token integration: Added logic to store tokens in Vuex (with localStorage persistence) for global access.
  • Fallback error handling: Added a default case to catch unforeseen status codes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:18:46