vue axios 实现登录
安装 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 并重定向到登录页面。
const logout = () => {
localStorage.removeItem('token');
window.location.href = '/login';
};






