vue登录模块实现
Vue 登录模块实现
创建登录表单组件
使用 Vue 的单文件组件结构,构建包含用户名和密码输入框的登录表单。表单需绑定 v-model 实现双向数据绑定,并添加提交事件处理。
<template>
<div class="login-container">
<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>
</div>
</template>
<script>
export default {
data() {
return {
form: {
username: "",
password: "",
},
};
},
methods: {
handleLogin() {
// 登录逻辑
},
},
};
</script>
表单验证
引入 Vuelidate 或手动验证,确保输入符合要求(如非空、长度限制等)。

import { required, minLength } from "vuelidate/lib/validators";
export default {
validations: {
form: {
username: { required, minLength: minLength(3) },
password: { required, minLength: minLength(6) },
},
},
methods: {
handleLogin() {
this.$v.$touch();
if (!this.$v.$invalid) {
// 提交逻辑
}
},
},
};
调用登录 API
使用 axios 发送登录请求,处理成功或失败的回调。
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("登录失败: " + error.response.data.message);
}
},
},
路由守卫配置
在 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 集中管理用户登录状态,便于跨组件共享数据。
// store.js
export default 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;
},
},
});
响应式布局与样式
添加基础样式确保表单在不同设备上显示正常。
.login-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
}
input {
width: 100%;
padding: 10px;
margin: 10px 0;
}
button {
width: 100%;
padding: 10px;
background: #42b983;
color: white;
border: none;
}






