vue 实现简单登陆
创建Vue项目
使用Vue CLI初始化项目:
vue create vue-login-demo
选择默认配置或手动配置(如Babel、Router等)。
安装必要依赖
若需使用Axios发送请求,安装它:

npm install axios
设计登录组件
在src/components/Login.vue中创建登录表单:
<template>
<div class="login">
<h3>用户登录</h3>
<form @submit.prevent="handleLogin">
<input v-model="username" type="text" placeholder="用户名" required />
<input v-model="password" type="password" placeholder="密码" required />
<button type="submit">登录</button>
</form>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: '',
errorMessage: ''
};
},
methods: {
async handleLogin() {
try {
const response = await axios.post('https://api.example.com/login', {
username: this.username,
password: this.password
});
localStorage.setItem('token', response.data.token);
this.$router.push('/dashboard');
} catch (error) {
this.errorMessage = '登录失败,请检查用户名或密码';
}
}
}
};
</script>
<style scoped>
.login {
max-width: 300px;
margin: 0 auto;
padding: 20px;
}
.error {
color: red;
}
</style>
配置路由
在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;
添加Dashboard组件
在src/components/Dashboard.vue中创建受保护页面:
<template>
<div>
<h3>欢迎进入仪表盘</h3>
<button @click="handleLogout">退出登录</button>
</div>
</template>
<script>
export default {
methods: {
handleLogout() {
localStorage.removeItem('token');
this.$router.push('/login');
}
}
};
</script>
运行项目
启动开发服务器:
npm run serve
关键点说明
- 表单使用
v-model双向绑定数据。 @submit.prevent阻止默认表单提交行为。- 通过Axios发送POST请求到模拟API(需替换为真实后端地址)。
- 使用
localStorage存储登录令牌(Token)。 - 路由守卫检查认证状态,未登录用户跳转到登录页。
注意事项
- 实际项目中应使用HTTPS和安全存储(如Vuex或Pinia管理状态)。
- 密码需加密传输,后端需验证并返回安全的Token。
- 可添加表单验证库(如VeeValidate)增强输入校验。






