当前位置:首页 > VUE

前端实现登录验证vue

2026-02-24 12:45:09VUE

前端实现登录验证(Vue)

使用 Vue 表单验证库(VeeValidate)

安装 VeeValidate 库:

npm install vee-validate

在 Vue 项目中引入并配置:

import { Form, Field, ErrorMessage } from 'vee-validate';
import * as yup from 'yup';

export default {
  components: {
    Form,
    Field,
    ErrorMessage,
  },
  data() {
    return {
      schema: yup.object({
        email: yup.string().required().email(),
        password: yup.string().required().min(6),
      }),
    };
  },
};

模板中使用:

<Form :validation-schema="schema" @submit="handleLogin">
  <Field name="email" type="email" />
  <ErrorMessage name="email" />

  <Field name="password" type="password" />
  <ErrorMessage name="password" />

  <button type="submit">登录</button>
</Form>

自定义验证规则

在 Vue 组件中定义本地验证规则:

methods: {
  validateEmail(value) {
    if (!value) return '邮箱不能为空';
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!regex.test(value)) return '请输入有效的邮箱地址';
    return true;
  },
  validatePassword(value) {
    if (!value) return '密码不能为空';
    if (value.length < 6) return '密码长度至少6位';
    return true;
  },
  handleSubmit() {
    this.$refs.form.validate().then(success => {
      if (success) {
        // 提交逻辑
      }
    });
  }
}

结合 Element UI 的表单验证

安装 Element UI:

npm install element-ui

使用示例:

<template>
  <el-form :model="loginForm" :rules="rules" ref="loginForm">
    <el-form-item prop="email">
      <el-input v-model="loginForm.email" placeholder="邮箱"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码"></el-input>
    </el-form-item>
    <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        email: '',
        password: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 提交逻辑
        }
      });
    }
  }
};
</script>

实现 JWT 认证流程

登录成功后处理 token:

axios.post('/api/login', this.loginForm)
  .then(response => {
    const token = response.data.token;
    localStorage.setItem('auth_token', token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    this.$router.push('/dashboard');
  })
  .catch(error => {
    console.error('登录失败:', error);
  });

路由守卫验证

在 router.js 中配置全局前置守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('auth_token');
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

表单状态反馈

添加加载状态和错误提示:

前端实现登录验证vue

data() {
  return {
    loading: false,
    errorMessage: ''
  };
},
methods: {
  async handleLogin() {
    this.loading = true;
    try {
      await authService.login(this.email, this.password);
      this.$router.push('/dashboard');
    } catch (error) {
      this.errorMessage = error.response?.data?.message || '登录失败';
    } finally {
      this.loading = false;
    }
  }
}

标签: vue
分享给朋友:

相关文章

项目基于vue实现

项目基于vue实现

基于Vue实现项目的关键方法 搭建基础环境 安装Node.js和npm/yarn,确保开发环境具备运行Vue的能力。通过Vue CLI快速初始化项目结构,选择所需配置(如Babel、Router、Vu…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue分类实现

vue分类实现

Vue分类实现方法 在Vue中实现分类功能通常涉及数据分组、动态渲染和交互逻辑。以下是几种常见的实现方式: 基于计算属性的分类 通过计算属性对原始数据进行分组处理,适合静态或少量数据分类: com…

vue实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdown…

vue实现getapp

vue实现getapp

Vue 中实现全局获取应用实例的方法 在 Vue 3 中,可以通过 getCurrentInstance 方法获取当前组件实例,但需要明确其使用场景和限制。以下是具体实现方式: 方法一:通过 get…

react实现vue

react实现vue

React 实现 Vue 功能 React 和 Vue 是两种不同的前端框架,但可以通过一些方法在 React 中实现 Vue 的特性。以下是几种常见 Vue 功能在 React 中的实现方式: 双…