当前位置:首页 > VUE

vue.js 实现登录

2026-01-21 16:12:47VUE

使用 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 存储:使用 localStorageHttpOnly Cookie。
  • 错误处理:显示友好的错误提示,避免暴露敏感信息。

通过以上步骤可实现基础的 Vue.js 登录功能,根据实际需求扩展验证、第三方登录等特性。

vue.js 实现登录

标签: vuejs
分享给朋友:

相关文章

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="w…

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-to…

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue实现模块

vue实现模块

Vue 实现模块化的方法 Vue 支持多种模块化开发方式,可以根据项目需求选择适合的方案。 使用单文件组件(SFC) 单文件组件是 Vue 最常用的模块化方式,将模板、脚本和样式封装在一个 .vue…