vue3.0登录实现
Vue 3.0 登录功能实现
准备工作
确保已安装 Vue 3.0 及相关依赖(如 Vue Router、Axios)。通过以下命令创建项目:
npm init vue@latest
创建登录组件
在 src/components 目录下创建 Login.vue 文件,包含表单和基础逻辑:
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button type="submit">登录</button>
</form>
</template>
<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
const username = ref('');
const password = ref('');
const router = useRouter();
const handleLogin = async () => {
try {
const response = await axios.post('/api/login', {
username: username.value,
password: password.value
});
localStorage.setItem('token', response.data.token);
router.push('/dashboard');
} catch (error) {
alert('登录失败');
}
};
</script>
配置路由
在 src/router/index.js 中设置登录路由和权限控制:
import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import Dashboard from '../components/Dashboard.vue';
const routes = [
{ path: '/login', component: Login },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !localStorage.getItem('token')) {
next('/login');
} else {
next();
}
});
export default router;
后端接口对接
使用 Axios 拦截器添加 token 到请求头:
// src/main.js 或单独封装 axios
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
状态管理(可选)
如需全局管理用户状态,可使用 Pinia:
// stores/auth.js
import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null,
isAuthenticated: !!localStorage.getItem('token')
}),
actions: {
login(userData) {
this.user = userData;
this.isAuthenticated = true;
}
}
});
表单验证(可选)
添加基础验证逻辑:
const validateForm = () => {
if (!username.value || !password.value) {
alert('请填写完整信息');
return false;
}
return true;
};
// 在 handleLogin 中调用
if (!validateForm()) return;
响应式样式
为登录表单添加基础样式:

<style scoped>
form {
display: flex;
flex-direction: column;
max-width: 300px;
margin: 0 auto;
}
input {
margin-bottom: 10px;
padding: 8px;
}
</style>






