当前位置:首页 > VUE

vue js实现登录

2026-01-18 23:15:13VUE

Vue.js 登录功能实现

依赖安装 确保项目已安装 Vue.js 和必要的依赖库(如 Vue Router、Axios)。通过以下命令安装:

npm install vue-router axios

路由配置router/index.js 中配置登录路由:

import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

登录页面组件 创建 Login.vue 文件,包含表单和提交逻辑:

<template>
  <div class="login-container">
    <form @submit.prevent="handleLogin">
      <input v-model="username" type="text" placeholder="用户名" required>
      <input v-model="password" type="password" placeholder="密码" required>
      <button type="submit">登录</button>
    </form>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      errorMessage: ''
    };
  },
  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) {
        this.errorMessage = '登录失败,请检查凭证';
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  max-width: 300px;
  margin: 0 auto;
}
.error {
  color: red;
}
</style>

API 请求处理 后端需提供 /api/login 接口接收 POST 请求。示例使用 Axios 发送请求,需根据实际 API 调整 URL 和参数。

vue js实现登录

状态管理(可选) 对于复杂应用,可使用 Vuex 或 Pinia 管理登录状态:

// Pinia 示例 (stores/auth.js)
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: false,
    user: null
  }),
  actions: {
    login(credentials) {
      return axios.post('/api/login', credentials)
        .then(response => {
          this.isAuthenticated = true;
          this.user = response.data.user;
          localStorage.setItem('token', response.data.token);
        });
    }
  }
});

路由守卫router/index.js 中添加全局前置守卫,限制未登录访问:

vue js实现登录

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');
  if (to.name !== 'Login' && !isAuthenticated) {
    next({ name: 'Login' });
  } else {
    next();
  }
});

表单验证增强 可引入 Vuelidate 或自定义验证逻辑:

// 示例:简单验证
methods: {
  validateForm() {
    return this.username.length > 3 && this.password.length > 6;
  },
  handleLogin() {
    if (!this.validateForm()) {
      this.errorMessage = '用户名或密码不符合要求';
      return;
    }
    // 继续登录逻辑
  }
}

响应式设计 通过 CSS 媒体查询优化移动端显示:

@media (max-width: 600px) {
  .login-container {
    padding: 20px;
  }
}

安全注意事项

  • 使用 HTTPS 传输数据
  • 后端应对密码进行哈希处理
  • 考虑实现 CSRF 保护
  • 敏感操作需二次验证

标签: vuejs
分享给朋友:

相关文章

vue实现多选div

vue实现多选div

实现多选 DIV 的基本思路 在 Vue 中实现多选 DIV 功能,可以通过以下方法实现。主要思路是利用 v-model 绑定选中状态,结合 CSS 类名动态切换样式。 数据准备与模板结构 定义一个…

vue实现点击旋转轮盘

vue实现点击旋转轮盘

实现点击旋转轮盘效果 在Vue中实现点击旋转轮盘效果,可以通过CSS动画和Vue的数据绑定结合完成。以下是一个完整的实现方案: 准备工作 需要安装Vue.js环境,可以通过CDN引入或使用Vue C…

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue实现图册

vue实现图册

Vue实现图册功能 在Vue中实现图册功能通常涉及图片展示、切换、缩放等交互效果。以下是常见的实现方法和关键代码示例: 基础图册组件结构 使用Vue单文件组件构建基础结构: <templat…

vue实现树

vue实现树

Vue 实现树形结构的方法 使用递归组件实现树形结构 递归组件是Vue中实现树形结构的常见方式。通过组件调用自身,可以轻松构建多层嵌套的树形数据。 <template> <ul…

vue实现接口

vue实现接口

在 Vue 中实现接口请求 Vue 本身不直接提供 HTTP 请求功能,通常需要借助第三方库如 axios 或 fetch 来实现接口请求。以下是几种常见方法: 使用 axios 发送请求 安装 a…