vue 实现登陆
Vue 登录功能实现
基础结构搭建
使用 Vue CLI 创建项目或直接在现有项目中添加登录功能。安装必要依赖如 vue-router 和 axios:
npm install vue-router axios
创建登录组件 Login.vue:
<template>
<div class="login-container">
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名"/>
<input v-model="password" type="password" placeholder="密码"/>
<button type="submit">登录</button>
</form>
</div>
</template>
状态管理
通过 Vuex 或组件内状态管理用户凭证:
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) {
alert('登录失败')
}
}
}
}
路由配置
在 router/index.js 中配置登录路由和权限控制:

const routes = [
{
path: '/login',
component: () => import('../views/Login.vue')
},
{
path: '/dashboard',
component: () => import('../views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
添加导航守卫实现路由保护:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!localStorage.getItem('token')) {
next('/login')
} else {
next()
}
} else {
next()
}
})
表单验证
使用 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) {
// 提交逻辑
}
}
}
}
安全增强
实现以下安全措施:
- 使用 HTTPS 传输数据
- 密码字段进行前端加密
- 设置 token 过期时间
- 添加 CSRF 防护
响应处理
完善登录后的响应处理逻辑:
handleLogin() {
axios.post('/api/login', credentials)
.then(response => {
if (response.data.success) {
commit('SET_USER', response.data.user)
commit('SET_TOKEN', response.data.token)
router.replace({ name: 'Home' })
}
})
.catch(error => {
if (error.response.status === 401) {
this.error = '无效凭证'
}
})
}
用户体验优化
添加加载状态和错误提示:
<template>
<button :disabled="loading" type="submit">
{{ loading ? '登录中...' : '登录' }}
</button>
<div v-if="error" class="error-message">{{ error }}</div>
</template>
以上实现方案可根据具体项目需求进行调整和扩展。






