vue连接实现登录功能
创建登录表单组件
在Vue项目中创建一个登录表单组件,通常命名为Login.vue。该组件包含用户名和密码输入框,以及提交按钮。
<template>
<div class="login">
<h2>登录</h2>
<form @submit.prevent="handleLogin">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" v-model="username" required>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" v-model="password" required>
</div>
<button type="submit">登录</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleLogin() {
// 登录逻辑将在这里实现
}
}
}
</script>
设置API请求
安装axios用于发送HTTP请求到后端API。
npm install axios
在项目中创建或使用现有的API服务文件,通常命名为api.js或auth.js。
import axios from 'axios';
const api = axios.create({
baseURL: 'http://your-api-url.com/api',
});
export const login = (credentials) => {
return api.post('/login', credentials);
};
实现登录逻辑
在登录组件的handleLogin方法中调用API服务。

import { login } from '@/api/auth';
methods: {
async handleLogin() {
try {
const response = await login({
username: this.username,
password: this.password
});
// 存储token或其他认证信息
localStorage.setItem('token', response.data.token);
// 重定向到主页或其他受保护的路由
this.$router.push('/dashboard');
} catch (error) {
console.error('登录失败:', error);
// 显示错误信息给用户
}
}
}
处理认证状态
创建Vuex store来管理用户认证状态。
// store/auth.js
const state = {
user: null,
isAuthenticated: false
};
const mutations = {
SET_USER(state, user) {
state.user = user;
state.isAuthenticated = !!user;
}
};
const actions = {
async login({ commit }, credentials) {
const response = await login(credentials);
commit('SET_USER', response.data.user);
localStorage.setItem('token', response.data.token);
return response.data.user;
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
创建路由守卫
设置路由守卫来保护需要认证的路由。

// router/index.js
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.auth.isAuthenticated;
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next('/login');
} else {
next();
}
});
添加导航守卫
在main.js或入口文件中添加导航守卫,检查用户是否已认证。
// main.js
import store from './store';
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters['auth/isAuthenticated']) {
next({
path: '/login',
query: { redirect: to.fullPath }
});
} else {
next();
}
} else {
next();
}
});
实现注销功能
添加注销功能,清除用户认证信息。
// store/auth.js
const actions = {
logout({ commit }) {
commit('SET_USER', null);
localStorage.removeItem('token');
}
};
在组件中调用注销action:
methods: {
handleLogout() {
this.$store.dispatch('auth/logout');
this.$router.push('/login');
}
}






