vue3实现登录
Vue3 实现登录功能
创建登录表单组件
使用 Vue3 的 Composition API 和 <script setup> 语法简化代码结构。以下是一个基础登录表单示例:
<template>
<form @submit.prevent="handleLogin">
<input v-model="form.username" type="text" placeholder="用户名" required>
<input v-model="form.password" type="password" placeholder="密码" required>
<button type="submit">登录</button>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
</form>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const form = ref({
username: '',
password: ''
})
const errorMessage = ref('')
const router = useRouter()
const authStore = useAuthStore()
const handleLogin = async () => {
try {
await authStore.login(form.value)
router.push('/dashboard')
} catch (error) {
errorMessage.value = error.response?.data?.message || '登录失败'
}
}
</script>
状态管理(Pinia)
使用 Pinia 管理用户认证状态和登录逻辑:

// stores/auth.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const isAuthenticated = ref(false)
const login = async (credentials) => {
const response = await api.post('/login', credentials)
user.value = response.data.user
isAuthenticated.value = true
localStorage.setItem('token', response.data.token)
}
const logout = () => {
user.value = null
isAuthenticated.value = false
localStorage.removeItem('token')
}
return { user, isAuthenticated, login, logout }
})
路由配置
配置路由守卫保护需要认证的页面:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/login', component: () => import('@/views/Login.vue') },
{
path: '/dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }
}
]
})
router.beforeEach((to) => {
const authStore = useAuthStore()
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
return '/login'
}
})
API 请求封装
使用 axios 封装 API 请求并添加请求拦截器:

// api/index.js
import axios from 'axios'
const api = axios.create({
baseURL: 'https://your-api-endpoint.com/api'
})
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
export default api
响应式布局优化
添加基础样式增强用户体验:
/* 登录表单样式 */
form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
input {
display: block;
width: 100%;
margin-bottom: 15px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
width: 100%;
padding: 10px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.error {
color: #ff5252;
margin-top: 10px;
}
表单验证
添加客户端表单验证逻辑:
const validateForm = () => {
if (!form.value.username.trim()) {
errorMessage.value = '请输入用户名'
return false
}
if (form.value.password.length < 6) {
errorMessage.value = '密码长度不能少于6位'
return false
}
return true
}
const handleLogin = async () => {
if (!validateForm()) return
// 其余登录逻辑...
}






