vue实现简单登录功能
创建Vue项目
使用Vue CLI初始化项目,确保已安装Node.js和Vue CLI。
npm install -g @vue/cli
vue create vue-login-demo
cd vue-login-demo
npm run serve
设计登录表单
在src/components下创建Login.vue,包含用户名、密码输入框和提交按钮。
<template>
<div>
<h3>登录</h3>
<form @submit.prevent="handleSubmit">
<input v-model="username" placeholder="用户名" type="text" required />
<input v-model="password" placeholder="密码" type="password" required />
<button type="submit">登录</button>
</form>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
errorMessage: ''
};
},
methods: {
handleSubmit() {
if (this.username === 'admin' && this.password === '123456') {
alert('登录成功');
this.$router.push('/dashboard'); // 假设有路由跳转
} else {
this.errorMessage = '用户名或密码错误';
}
}
}
};
</script>
<style scoped>
.error { color: red; }
</style>
配置路由
安装Vue Router并配置登录页路由。
npm install vue-router
在src/router/index.js中设置路由:

import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
const routes = [
{ path: '/login', component: Login },
// 其他路由...
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
状态管理(可选)
使用Vuex或Pinia管理登录状态。以Pinia为例:
npm install pinia
创建src/stores/auth.js:

import { defineStore } from 'pinia';
export const useAuthStore = defineStore('auth', {
state: () => ({
isAuthenticated: false,
user: null
}),
actions: {
login(username, password) {
if (username === 'admin' && password === '123456') {
this.isAuthenticated = true;
this.user = { username };
return true;
}
return false;
}
}
});
在Login.vue中调用:
import { useAuthStore } from '../stores/auth';
export default {
setup() {
const authStore = useAuthStore();
const handleSubmit = () => {
if (authStore.login(username.value, password.value)) {
router.push('/dashboard');
}
};
return { handleSubmit };
}
};
表单验证增强
使用Vuelidate或原生验证提升用户体验:
npm install vuelidate
示例规则:
import { required, minLength } from 'vuelidate/lib/validators';
export default {
validations: {
username: { required },
password: { required, minLength: minLength(6) }
}
};
安全注意事项
- 实际项目中需后端验证,避免前端硬编码凭证。
- 使用HTTPS传输敏感数据。
- 密码应加密存储(如bcrypt)。






