使用Vue開發(fā)登錄頁面的完整指南
一、項目搭建與基礎(chǔ)配置
環(huán)境準(zhǔn)備
使用 Vue CLI 或 Vite 創(chuàng)建項目,推薦組合:Vue3 + Element Plus + Vue Router
npm create vue@latest npm install element-plus @element-plus/icons-vue vue-router
- 全局配置(main.js)
import { createApp } from 'vue' import ElementPlus from 'element-plus' import router from './router' import 'element-plus/dist/index.css' const app = createApp(App) app.use(ElementPlus) app.use(router) app.mount('#app')
二、登錄頁面核心實現(xiàn)
- 模板結(jié)構(gòu)(login.vue)
<template> <div class="login-container"> <el-form ref="formRef" :model="form" :rules="rules"> <h2 class="title">校園交易平臺</h2> <el-form-item prop="username"> <el-input v-model="form.username" prefix-icon="User" placeholder="請輸入手機號" /> </el-form-item> <el-form-item prop="password"> <el-input v-model="form.password" prefix-icon="Lock" type="password" show-password placeholder="請輸入密碼" @keyup.enter="handleLogin" /> </el-form-item> <el-button type="primary" :loading="loading" @click="handleLogin" > 登錄 </el-button> <div class="links"> <router-link to="/register">立即注冊</router-link> <router-link to="/forgot">忘記密碼?</router-link> </div> </el-form> </div> </template>
- 數(shù)據(jù)與驗證邏輯
<script setup> import { ref, reactive } from 'vue' import { useRouter } from 'vue-router' import { ElMessage } from 'element-plus' const form = reactive({ username: '', password: '' }) const rules = reactive({ username: [ { required: true, message: '請輸入手機號', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手機號格式錯誤' } ], password: [ { required: true, message: '請輸入密碼', trigger: 'blur' }, { min: 6, max: 16, message: '長度6-16位' } ] }) const loading = ref(false) const formRef = ref(null) const router = useRouter() const handleLogin = async () => { try { await formRef.value.validate() loading.value = true // 模擬API請求 await new Promise(resolve => setTimeout(resolve, 1000)) sessionStorage.setItem('token', 'demo_token') ElMessage.success('登錄成功') router.replace('/dashboard') } catch (error) { console.error('登錄失敗:', error) } finally { loading.value = false } } </script>
- 樣式優(yōu)化要點
<style scoped> .login-container { height: 100vh; display: grid; place-items: center; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); } .title { text-align: center; margin-bottom: 2rem; color: #2c3e50; font-size: 1.8rem; } :deep(.el-form) { width: 400px; padding: 2rem; background: rgba(255,255,255,0.95); border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .el-button { width: 100%; margin-top: 1rem; } .links { margin-top: 1.5rem; display: flex; justify-content: space-between; a { color: #409eff; text-decoration: none; transition: color 0.3s; &:hover { color: #66b1ff; } } } </style>
三、進階功能實現(xiàn)
- 路由守衛(wèi)配置
// router/index.js router.beforeEach((to) => { const isAuthenticated = sessionStorage.getItem('token') if (to.meta.requiresAuth && !isAuthenticated) { return '/login' } if (to.path === '/login' && isAuthenticated) { return '/dashboard' } })
- 安全增強方案
密碼加密傳輸(使用crypto-js)
添加驗證碼功能
請求限流與防重放攻擊
import CryptoJS from 'crypto-js' const encryptPassword = (password) => { return CryptoJS.SHA256(password).toString() }
- 第三方登錄集成
<template> <div class="oauth-login"> <el-divider>第三方登錄</el-divider> <div class="oauth-buttons"> <el-button @click="handleWechatLogin"> <svg-icon icon-class="wechat" /> 微信登錄 </el-button> </div> </div> </template>
四、最佳實踐與注意事項
表單驗證優(yōu)化
異步驗證手機號是否注冊
密碼強度實時檢測
const checkUsername = async (rule, value, callback) => { if (!value) return callback(new Error('請輸入手機號')) if (!/^1[3-9]\d{9}$/.test(value)) return callback(new Error('格式錯誤')) try { const { data } = await api.checkUsername(value) if (!data.exist) callback(new Error('該用戶未注冊')) } catch (error) { callback(new Error('驗證失敗')) } }
- 用戶體驗優(yōu)化
自動填充最近登錄賬號
記住密碼功能(加密存儲)
加載狀態(tài)管理
// 自動填充 const lastUsername = localStorage.getItem('lastUsername') if (lastUsername) form.username = lastUsername // 記住密碼 const savePassword = ref(false) watch(savePassword, (val) => { if (val) { localStorage.setItem('remembered', JSON.stringify(form)) } else { localStorage.removeItem('remembered') } })
- 錯誤處理規(guī)范
try { const res = await loginApi(formData) if (res.code === 1001) { ElMessage.warning('該賬號已被凍結(jié)') } } catch (err) { ElMessage.error({ message: `登錄失敗: ${err.message}`, grouping: true // 相同錯誤合并顯示 }) }
五、典型問題解決方案
跨域問題處理
// vite.config.js export default defineConfig({ server: { proxy: { '/api': { target: 'http://backend.example.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } })
- 響應(yīng)式布局適配
@media (max-width: 768px) { .login-container { padding: 1rem; :deep(.el-form) { width: 100%; margin: 0 1rem; } } }
瀏覽器兼容問題
使用@vitejs/plugin-legacy處理ES6+語法
添加autoprefixer自動補全CSS前綴
到此這篇關(guān)于使用Vue開發(fā)登錄頁面的完整指南的文章就介紹到這了,更多相關(guān)Vue開發(fā)登錄頁面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端vue中實現(xiàn)文件下載的幾種方法總結(jié)
這篇文章主要介紹了前端vue中實現(xiàn)文件下載的幾種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04vue style屬性設(shè)置背景圖片的相對路徑無效的解決
這篇文章主要介紹了vue style屬性設(shè)置背景圖片的相對路徑無效的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vue3?組合式api中?ref?和$parent?的使用方法
vue3中, 在 組件中添加一個 component ref=“xxx” ,就可以在父組件中得到 子組件的 dom 對象, 以及 虛擬的 dom 對象, 有了虛擬 dom, 我們就可以在父組件中控制子組件的顯示了,這篇文章主要介紹了vue3組合式api中ref和$parent的使用,需要的朋友可以參考下2023-09-09vue - vue.config.js中devServer配置方式
今天小編就為大家分享一篇vue - vue.config.js中devServer配置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10