当前位置:首页 > 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 组件中定义本地验证规则:

前端实现登录验证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

使用示例:

前端实现登录验证vue

<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();
  }
});

表单状态反馈

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

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
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{…

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue 实现挂载

vue 实现挂载

Vue 实现挂载的基本方法 在 Vue 中,挂载是将 Vue 实例与 DOM 元素关联的过程。通过挂载,Vue 可以管理 DOM 并实现数据绑定和响应式更新。 创建 Vue 实例并挂载 const…

vue 实现打印

vue 实现打印

Vue 实现打印功能的方法 在Vue项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。 //…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们…