vue实现登了页面
Vue 实现登录页面
使用 Vue 实现登录页面通常需要结合 Vue 的核心功能(如数据绑定、事件处理)和 Vue Router 进行页面跳转。以下是一个完整的实现方案:
1. 创建 Vue 项目
确保已安装 Vue CLI,通过以下命令创建项目:
vue create vue-login-demo
2. 安装 Vue Router
在项目目录中运行:
npm install vue-router
3. 项目结构
典型结构如下:
src/
├── components/
│ └── Login.vue
├── router/
│ └── index.js
├── App.vue
└── main.js
4. 实现登录组件 (Login.vue)
<template>
<div class="login-container">
<h2>登录</h2>
<form @submit.prevent="handleSubmit">
<div class="form-group">
<label for="username">用户名</label>
<input
type="text"
id="username"
v-model="username"
required
/>
</div>
<div class="form-group">
<label for="password">密码</label>
<input
type="password"
id="password"
v-model="password"
required
/>
</div>
<button type="submit">登录</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
handleSubmit() {
// 模拟登录逻辑
if (this.username && this.password) {
localStorage.setItem('isAuthenticated', 'true')
this.$router.push('/dashboard')
} else {
alert('请输入用户名和密码')
}
}
}
}
</script>
<style scoped>
.login-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
</style>
5. 配置路由 (router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Dashboard from '../components/Dashboard.vue'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '*',
redirect: '/login'
}
]
})
// 路由守卫
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('isAuthenticated')
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
next('/login')
} else {
next()
}
})
export default router
6. 修改主文件 (main.js)
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
7. 修改 App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
8. 创建 Dashboard 组件
<template>
<div>
<h2>欢迎来到仪表盘</h2>
<button @click="handleLogout">退出登录</button>
</div>
</template>
<script>
export default {
methods: {
handleLogout() {
localStorage.removeItem('isAuthenticated')
this.$router.push('/login')
}
}
}
</script>
9. 运行项目
npm run serve
10. 扩展功能建议
- 添加表单验证(可使用 Vuelidate 或 VeeValidate)
- 集成真实的 API 调用(使用 axios)
- 添加加载状态和错误处理
- 实现记住我功能
- 添加第三方登录(如 Google、GitHub)
这个实现包含了基本的登录功能、路由保护和状态管理(使用 localStorage)。根据实际需求,可以进一步扩展和完善功能。







