当前位置:首页 > VUE

vue实现登录注册

2026-01-11 20:17:23VUE

Vue 登录注册功能实现

项目初始化

使用 Vue CLI 创建项目,安装必要依赖(如 Vue Router、Axios):

vue create auth-demo
cd auth-demo
npm install vue-router axios

路由配置

src/router/index.js 中设置登录/注册路由:

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

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register }
]

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

export default router

登录组件实现

src/views/Login.vue 示例:

<template>
  <form @submit.prevent="handleLogin">
    <input v-model="email" type="email" placeholder="Email">
    <input v-model="password" type="password" placeholder="Password">
    <button type="submit">Login</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      email: '',
      password: ''
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('/api/login', {
          email: this.email,
          password: this.password
        })
        localStorage.setItem('token', response.data.token)
        this.$router.push('/dashboard')
      } catch (error) {
        alert('Login failed')
      }
    }
  }
}
</script>

注册组件实现

src/views/Register.vue 示例:

vue实现登录注册

<template>
  <form @submit.prevent="handleRegister">
    <input v-model="name" type="text" placeholder="Name">
    <input v-model="email" type="email" placeholder="Email">
    <input v-model="password" type="password" placeholder="Password">
    <button type="submit">Register</button>
  </form>
</template>

<script>
export default {
  data() {
    return {
      name: '',
      email: '',
      password: ''
    }
  },
  methods: {
    async handleRegister() {
      try {
        await axios.post('/api/register', {
          name: this.name,
          email: this.email,
          password: this.password
        })
        this.$router.push('/login')
      } catch (error) {
        alert('Registration failed')
      }
    }
  }
}
</script>

状态管理(可选)

对于复杂应用可引入 Pinia/Vuex:

// stores/auth.js
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null
  }),
  actions: {
    async login(credentials) {
      const res = await axios.post('/api/login', credentials)
      this.token = res.data.token
      localStorage.setItem('token', this.token)
    },
    logout() {
      this.token = null
      localStorage.removeItem('token')
    }
  }
})

表单验证

推荐使用 VeeValidate 或自定义验证:

vue实现登录注册

methods: {
  validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return re.test(email)
  },
  validatePassword(password) {
    return password.length >= 6
  }
}

API 拦截器

设置 Axios 全局拦截器:

// src/utils/axios.js
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

路由守卫

添加导航守卫保护私有路由:

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

样式优化

建议使用 Tailwind CSS 或 SCSS 美化表单:

form {
  @apply max-w-md mx-auto p-6 bg-white rounded shadow-md;
}
input {
  @apply w-full px-3 py-2 mb-4 border rounded;
}
button {
  @apply w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600;
}

实际开发时需要根据后端 API 调整请求参数和响应处理,建议采用 JWT 进行身份验证,并实现密码加密传输(HTTPS)。

标签: vue
分享给朋友:

相关文章

vue实现前端分离

vue实现前端分离

Vue 实现前后端分离 前后端分离是一种架构模式,前端负责页面渲染和交互逻辑,后端提供数据接口。Vue.js 作为前端框架,非常适合实现前后端分离的开发模式。 核心实现步骤 创建 Vue 项目 使用…

vue的艾特功能实现

vue的艾特功能实现

Vue 的 @ 功能实现 在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法: 监听输入框内容 使用 v-model 绑定输入框内容,并通过 @…

vue实现详情

vue实现详情

Vue 实现详情页的常见方法 使用动态路由 在 Vue Router 中配置动态路由参数,通过 $route.params 获取详情 ID。示例路由配置: { path: '/detail/:i…

vue实现$.extend

vue实现$.extend

Vue 实现类似 jQuery 的 $.extend 功能 在 Vue 中实现类似 jQuery 的 $.extend 功能,可以通过多种方式完成。$.extend 主要用于合并多个对象的属性,Vue…

vue实现erp

vue实现erp

Vue实现ERP系统的关键步骤 技术选型与架构设计 采用Vue 3 + TypeScript构建前端,搭配Pinia状态管理,Element Plus或Ant Design Vue作为UI框架。后端可…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装…