当前位置:首页 > VUE

vue axios 实现登录

2026-03-10 02:11:28VUE

安装 Axios

在 Vue 项目中安装 Axios,可以通过 npm 或 yarn 进行安装。

npm install axios
# 或
yarn add axios

配置 Axios

在项目中创建一个单独的文件(如 src/api/axios.js)配置 Axios 实例,设置基础 URL 和拦截器。

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://your-api-domain.com/api',
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    if (error.response.status === 401) {
      // 处理未授权情况
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default instance;

创建登录方法

在 Vue 组件或单独的服务文件中调用登录接口。

import axios from './api/axios';

const login = async (credentials) => {
  try {
    const response = await axios.post('/login', credentials);
    localStorage.setItem('token', response.data.token);
    return response;
  } catch (error) {
    throw error;
  }
};

export { login };

在 Vue 组件中使用

在登录页面组件中调用登录方法,处理用户输入和登录逻辑。

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="email" type="email" placeholder="Email" required />
    <input v-model="password" type="password" placeholder="Password" required />
    <button type="submit">Login</button>
  </form>
</template>

<script>
import { login } from '@/api/auth';

export default {
  data() {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    async handleLogin() {
      try {
        const response = await login({
          email: this.email,
          password: this.password,
        });
        this.$router.push('/dashboard');
      } catch (error) {
        alert('Login failed: ' + error.message);
      }
    },
  },
};
</script>

处理 Token 存储

登录成功后,将 token 存储到本地存储(localStorage)或 Vuex 中,并在后续请求中自动附加 token。

路由守卫

配置路由守卫,确保未登录用户无法访问受保护的路由。

import router from './router';
import { isAuthenticated } from './utils/auth';

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

注销功能

实现注销功能,清除本地存储的 token 并重定向到登录页面。

vue axios 实现登录

const logout = () => {
  localStorage.removeItem('token');
  window.location.href = '/login';
};

标签: vueaxios
分享给朋友:

相关文章

vue自己实现下拉导航

vue自己实现下拉导航

实现下拉导航的基本思路 在Vue中实现下拉导航,可以通过结合Vue的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…

vue实现框选

vue实现框选

Vue 实现框选功能 在 Vue 中实现框选功能通常需要监听鼠标事件,计算选区范围,并根据选区范围高亮或选中元素。以下是实现框选功能的关键步骤。 监听鼠标事件 在 Vue 模板中,为容器元素绑定鼠标…

vue实现投票

vue实现投票

Vue实现投票功能 数据准备 在Vue组件的data中定义投票相关数据,包括选项列表和当前选中状态: data() { return { options: [ { id: 1…

vue  实现关联属性

vue 实现关联属性

Vue 实现关联属性 在 Vue 中实现关联属性通常涉及计算属性(computed properties)或侦听器(watchers),用于根据其他属性的变化动态更新目标属性。 使用计算属性 计算属…

vue实现文字复制

vue实现文字复制

Vue 实现文字复制的几种方法 使用 Clipboard API 在 Vue 中可以通过调用浏览器的 Clipboard API 实现文字复制功能。该方法兼容现代浏览器,无需额外依赖。 method…