当前位置:首页 > VUE

vue实现登录调用接口

2026-01-20 05:51:55VUE

Vue 登录接口调用实现

安装 axios
在项目中安装 axios 用于发送 HTTP 请求:

npm install axios

创建 API 服务文件
src 目录下创建 api/auth.js 文件,封装登录接口:

import axios from 'axios';

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

export const login = (credentials) => {
  return authApi.post('/login', credentials);
};

登录组件实现
在 Vue 组件中调用接口(示例为 Login.vue):

vue实现登录调用接口

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="username" placeholder="用户名"/>
    <input v-model="password" type="password" placeholder="密码"/>
    <button type="submit">登录</button>
  </form>
</template>

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

export default {
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    async handleLogin() {
      try {
        const response = await login({
          username: this.username,
          password: this.password
        });
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      } catch (error) {
        alert('登录失败: ' + error.response?.data?.message || error.message);
      }
    }
  }
};
</script>

请求拦截器(可选)

auth.js 中添加拦截器处理请求头:

authApi.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

响应拦截器(可选)

处理通用错误响应:

vue实现登录调用接口

authApi.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      localStorage.removeItem('token');
      window.location.reload();
    }
    return Promise.reject(error);
  }
);

环境变量配置

在项目根目录创建 .env 文件:

VUE_APP_API_BASE_URL=https://your-api-endpoint.com/api

修改 auth.js 中的 baseURL

baseURL: process.env.VUE_APP_API_BASE_URL

TypeScript 支持(可选)

为接口定义类型:

interface LoginCredentials {
  username: string;
  password: string;
}

interface LoginResponse {
  token: string;
  expiresIn: number;
}

标签: 接口vue
分享给朋友:

相关文章

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-se…

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2ca…

vue列表实现

vue列表实现

Vue 列表实现方法 使用 v-for 指令 v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items 或 (item, index)…

vue 实现挂载

vue 实现挂载

Vue 实现挂载的基本方法 在 Vue 中,挂载是将 Vue 实例与 DOM 元素关联的过程。通过挂载,Vue 可以管理 DOM 并实现数据绑定和响应式更新。 创建 Vue 实例并挂载 const…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项…

vue实现换肤

vue实现换肤

使用 CSS 变量实现换肤 在 Vue 项目中,可以通过 CSS 变量(Custom Properties)动态切换主题色。CSS 变量可以在运行时修改,适合实现换肤功能。 定义全局 CSS 变量:…