vue实现登录注册
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 示例:

<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 或自定义验证:

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)。






