vue.js 实现登录
使用 Vue.js 实现登录功能
1. 创建 Vue 项目
使用 Vue CLI 初始化项目:
vue create login-app
选择默认配置或手动配置(如 Babel、Router、Vuex 等)。
2. 安装依赖
若需发送 HTTP 请求,安装 Axios:
npm install axios
3. 创建登录组件
在 src/components/Login.vue 中编写登录表单:
<template>
<div>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
<p v-if="error">{{ error }}</p>
</div>
</template>
<script>
export default {
data() {
return {
username: "",
password: "",
error: "",
};
},
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 (err) {
this.error = "登录失败,请检查用户名或密码";
}
},
},
};
</script>
4. 配置路由
在 src/router/index.js 中设置登录路由:
import Vue from "vue";
import Router from "vue-router";
import Login from "../components/Login.vue";
Vue.use(Router);
export default new Router({
routes: [{ path: "/login", component: Login }],
});
5. 处理 API 请求
在 src/api/auth.js 中封装登录接口:
import axios from "axios";
export const login = (credentials) => {
return axios.post("/api/login", credentials);
};
6. 状态管理(可选)
使用 Vuex 管理用户登录状态:
// src/store/index.js
export default new Vuex.Store({
state: { user: null, token: null },
mutations: {
setUser(state, payload) {
state.user = payload.user;
state.token = payload.token;
},
},
actions: {
async login({ commit }, credentials) {
const response = await login(credentials);
commit("setUser", response.data);
},
},
});
7. 保护路由
通过路由守卫限制未登录访问:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem("token");
if (to.path !== "/login" && !isAuthenticated) {
next("/login");
} else {
next();
}
});
8. 后端对接
确保后端提供 /api/login 接口,返回 JWT 或 session 凭证。
9. 样式优化
添加 CSS 或使用 UI 库(如 Element UI、Vuetify)美化表单。
10. 测试与调试
使用浏览器开发者工具检查网络请求,确保数据传递和状态更新正确。
关键注意事项
- 安全性:密码传输需 HTTPS,避免明文存储。
- Token 存储:使用
localStorage或HttpOnlyCookie。 - 错误处理:显示友好的错误提示,避免暴露敏感信息。
通过以上步骤可实现基础的 Vue.js 登录功能,根据实际需求扩展验证、第三方登录等特性。







