vue实现后台登录
Vue 实现后台登录功能
创建登录组件
在 src/views 目录下创建 Login.vue 文件,包含表单、输入框和提交按钮。表单需绑定 v-model 实现双向数据绑定。
<template>
<div class="login-container">
<form @submit.prevent="handleLogin">
<input v-model="form.username" placeholder="用户名" />
<input v-model="form.password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: ''
}
}
},
methods: {
handleLogin() {
// 登录逻辑
}
}
}
</script>
配置路由
在 src/router/index.js 中配置登录页路由,设置为公开路由(无需鉴权)。

const routes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue')
}
]
实现登录请求
通过 Axios 发送登录请求到后端 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('登录失败')
}
}
}
路由守卫
在路由配置中添加全局前置守卫,检查用户是否已登录。

router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token')
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
状态管理(可选)
使用 Vuex 集中管理用户登录状态和 token。
const store = new Vuex.Store({
state: {
token: null
},
mutations: {
setToken(state, token) {
state.token = token
}
}
})
样式优化
添加基础样式增强用户体验,例如错误提示和加载状态。
.login-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
}
.error-message {
color: red;
}






