vue登录实现方法
Vue 登录功能实现方法
前端实现(Vue.js)
创建登录表单组件
使用 Vue 的单文件组件创建登录表单,包含用户名和密码输入框以及提交按钮。通过 v-model 实现双向数据绑定。
<template>
<div class="login-form">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button @click="handleLogin">登录</button>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
async handleLogin() {
try {
const response = await axios.post('/api/login', {
username: this.username,
password: this.password
})
localStorage.setItem('token', response.data.token)
this.$router.push('/dashboard')
} catch (error) {
console.error('登录失败', error)
}
}
}
}
</script>
后端API对接
使用 Axios 发送登录请求
安装 axios 并配置基础 URL 和请求拦截器。
import axios from 'axios'
axios.defaults.baseURL = 'http://your-api-domain.com'
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
路由守卫配置
设置路由守卫保护需要认证的路由
在 Vue Router 中配置全局前置守卫,检查用户是否已登录。
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next('/login')
} else {
next()
}
})
状态管理(Vuex)
使用 Vuex 管理用户登录状态
创建 store 模块存储用户信息和登录状态。
const store = new Vuex.Store({
state: {
user: null,
isAuthenticated: false
},
mutations: {
setUser(state, user) {
state.user = user
state.isAuthenticated = true
},
logout(state) {
state.user = null
state.isAuthenticated = false
}
},
actions: {
login({ commit }, credentials) {
return axios.post('/api/login', credentials)
.then(response => {
commit('setUser', response.data.user)
localStorage.setItem('token', response.data.token)
})
}
}
})
安全注意事项
实现 JWT 过期处理
在响应拦截器中检查 token 是否过期,若过期则跳转至登录页。
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
store.commit('logout')
router.push('/login')
}
return Promise.reject(error)
}
)
表单验证
添加客户端表单验证
使用 Vuelidate 或自定义验证方法确保输入符合要求。
import { required, minLength } from 'vuelidate/lib/validators'
export default {
validations: {
username: { required },
password: { required, minLength: minLength(6) }
},
methods: {
handleLogin() {
this.$v.$touch()
if (!this.$v.$invalid) {
// 提交表单
}
}
}
}






