vue实现前端登录
Vue 前端登录实现方案
基础登录表单实现
使用 Vue 的模板语法创建登录表单,包含用户名和密码输入框。通过 v-model 实现双向数据绑定,监听表单提交事件。
<template>
<form @submit.prevent="handleLogin">
<input v-model="form.username" type="text" placeholder="用户名">
<input v-model="form.password" type="password" placeholder="密码">
<button type="submit">登录</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: ''
}
}
},
methods: {
handleLogin() {
// 登录逻辑
}
}
}
</script>
登录请求发送
通过 axios 或其他 HTTP 客户端发送登录请求到后端 API。处理响应结果,成功时保存 token 并跳转页面。
methods: {
async handleLogin() {
try {
const response = await axios.post('/api/login', this.form)
localStorage.setItem('token', response.data.token)
this.$router.push('/dashboard')
} catch (error) {
alert('登录失败')
}
}
}
路由守卫配置
在 Vue Router 中配置全局前置守卫,保护需要认证的路由。检查本地存储中的 token 是否存在。
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
状态管理集成
使用 Vuex 集中管理用户认证状态,包括登录状态和用户信息。创建专门的 auth 模块处理认证相关逻辑。
const authModule = {
state: () => ({
user: null,
isAuthenticated: false
}),
mutations: {
SET_USER(state, user) {
state.user = user
state.isAuthenticated = true
}
},
actions: {
login({ commit }, credentials) {
return axios.post('/api/login', credentials)
.then(response => {
commit('SET_USER', response.data.user)
localStorage.setItem('token', response.data.token)
})
}
}
}
错误处理和验证
添加表单验证逻辑,处理网络请求错误。使用第三方验证库如 VeeValidate 或手动实现验证规则。
methods: {
validateForm() {
if (!this.form.username) {
this.error = '请输入用户名'
return false
}
if (!this.form.password) {
this.error = '请输入密码'
return false
}
return true
},
async handleLogin() {
if (!this.validateForm()) return
// 登录逻辑
}
}
Token 自动刷新
实现 token 自动刷新机制,在 token 即将过期时自动请求新 token。使用 axios 拦截器处理 token 刷新逻辑。
axios.interceptors.response.use(response => response, async error => {
if (error.response.status === 401 && !error.config._retry) {
error.config._retry = true
const newToken = await refreshToken()
localStorage.setItem('token', newToken)
return axios(error.config)
}
return Promise.reject(error)
})
社交登录集成
支持第三方登录如 Google 或 GitHub OAuth。配置相应的 SDK 并处理回调。
methods: {
handleGoogleLogin() {
window.location.href = 'https://accounts.google.com/o/oauth2/auth?' +
'client_id=YOUR_CLIENT_ID&' +
'redirect_uri=YOUR_REDIRECT_URI&' +
'response_type=code&' +
'scope=email profile'
}
}
安全增强措施
实现 CSRF 防护,设置 HttpOnly cookie,添加登录尝试限制等安全措施。

axios.defaults.withCredentials = true
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'






