网页登录实现vue
使用 Vue 实现网页登录功能
创建 Vue 项目
使用 Vue CLI 初始化项目,运行命令 vue create login-demo 选择默认配置或手动配置项目。
安装必要依赖如 axios 用于网络请求,vue-router 用于页面导航:
npm install axios vue-router
设计登录页面组件
在 src/components/Login.vue 中创建登录表单,包含用户名、密码输入框和提交按钮:

<template>
<div class="login">
<h3>用户登录</h3>
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button @click="handleLogin">登录</button>
<p v-if="error" class="error">{{ error }}</p>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
error: ''
}
},
methods: {
async handleLogin() {
try {
const response = await axios.post('/api/login', {
username: this.username,
password: this.password
})
localStorage.setItem('token', response.data.token)
this.$router.push('/dashboard')
} catch (err) {
this.error = '登录失败,请检查凭证'
}
}
}
}
</script>
<style scoped>
.error { color: red; }
</style>
配置路由和状态管理
在 src/router/index.js 中设置路由,保护需要认证的路由:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import Dashboard from '@/components/Dashboard'
Vue.use(Router)
const router = new Router({
routes: [
{ path: '/login', component: Login },
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true }
}
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!localStorage.getItem('token')) {
next('/login')
} else {
next()
}
} else {
next()
}
})
export default router
实现 API 请求拦截
在 src/main.js 中配置 axios 全局拦截器,自动附加认证令牌:

import axios from 'axios'
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
}, error => {
return Promise.reject(error)
})
添加注销功能
在需要注销的组件中添加方法清除本地存储的令牌并重定向:
methods: {
logout() {
localStorage.removeItem('token')
this.$router.push('/login')
}
}
表单验证增强
使用 Vuelidate 或自定义验证逻辑增强表单安全性:
import { required, minLength } from 'vuelidate/lib/validators'
export default {
validations: {
username: { required },
password: { required, minLength: minLength(6) }
},
methods: {
handleLogin() {
this.$v.$touch()
if (!this.$v.$invalid) {
// 提交逻辑
}
}
}
}
响应式布局优化
通过媒体查询确保登录页面在不同设备上显示正常:
@media (max-width: 600px) {
.login {
width: 90%;
margin: 0 auto;
}
input, button {
width: 100%;
}
}






