登錄頁面的主要功能就是表單校驗(yàn)和登錄登出業(yè)務(wù)。
賬號(hào)密碼
account | password |
---|---|
cdshi0080 | 123456 |
cdshi0081 | 123456 |
cdshi0082 | 123456 |
cdshi0083 | 123456 |
cdshi0084 | 123456 |
cdshi0085 | 123456 |
cdshi0086 | 123456 |
cdshi0087 | 123456 |
cdshi0088 | 123456 |
路由配置
模版代碼
在 src\views\Login\index.vue 中添加登錄頁代碼:
<script setup>
</script>
<template>
<div>
<header class="login-header">
<div class="container m-top-20">
<h1 class="logo">
<RouterLink to="/">小兔鮮</RouterLink>
</h1>
<RouterLink class="entry" to="/">
進(jìn)入網(wǎng)站首頁
<i class="iconfont icon-angle-right"></i>
<i class="iconfont icon-angle-right"></i>
</RouterLink>
</div>
</header>
<section class="login-section">
<div class="wrapper">
<nav>
<a href="javascript:;">賬戶登錄</a>
</nav>
<div class="account-box">
<div class="form">
<el-form label-position="right" label-width="60px"
status-icon>
<el-form-item label="賬戶">
<el-input/>
</el-form-item>
<el-form-item label="密碼">
<el-input/>
</el-form-item>
<el-form-item label-width="22px">
<el-checkbox size="large">
我已同意隱私條款和服務(wù)條款
</el-checkbox>
</el-form-item>
<el-button size="large" class="subBtn">點(diǎn)擊登錄</el-button>
</el-form>
</div>
</div>
</div>
</section>
<footer class="login-footer">
<div class="container">
<p>
<a href="javascript:;">關(guān)于我們</a>
<a href="javascript:;">幫助中心</a>
<a href="javascript:;">售后服務(wù)</a>
<a href="javascript:;">配送與驗(yàn)收</a>
<a href="javascript:;">商務(wù)合作</a>
<a href="javascript:;">搜索推薦</a>
<a href="javascript:;">友情鏈接</a>
</p>
<p>CopyRight © 小兔鮮兒</p>
</div>
</footer>
</div>
</template>
<style scoped lang='scss'>
.login-header {
background: #fff;
border-bottom: 1px solid #e4e4e4;
.container {
display: flex;
align-items: flex-end;
justify-content: space-between;
}
.logo {
width: 200px;
a {
display: block;
height: 132px;
width: 100%;
text-indent: -9999px;
background: url("@/assets/images/logo.png") no-repeat center 18px / contain;
}
}
.sub {
flex: 1;
font-size: 24px;
font-weight: normal;
margin-bottom: 38px;
margin-left: 20px;
color: #666;
}
.entry {
width: 120px;
margin-bottom: 38px;
font-size: 16px;
i {
font-size: 14px;
color: $xtxColor;
letter-spacing: -5px;
}
}
}
.login-section {
background: url('@/assets/images/login-bg.png') no-repeat center / cover;
height: 488px;
position: relative;
.wrapper {
width: 380px;
background: #fff;
position: absolute;
left: 50%;
top: 54px;
transform: translate3d(100px, 0, 0);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
nav {
font-size: 14px;
height: 55px;
margin-bottom: 20px;
border-bottom: 1px solid #f5f5f5;
display: flex;
padding: 0 40px;
text-align: right;
align-items: center;
a {
flex: 1;
line-height: 1;
display: inline-block;
font-size: 18px;
position: relative;
text-align: center;
}
}
}
}
.login-footer {
padding: 30px 0 50px;
background: #fff;
p {
text-align: center;
color: #999;
padding-top: 20px;
a {
line-height: 1;
padding: 0 10px;
color: #999;
display: inline-block;
~a {
border-left: 1px solid #ccc;
}
}
}
}
.account-box {
.toggle {
padding: 15px 40px;
text-align: right;
a {
color: $xtxColor;
i {
font-size: 14px;
}
}
}
.form {
padding: 0 20px 20px 20px;
&-item {
margin-bottom: 28px;
.input {
position: relative;
height: 36px;
>i {
width: 34px;
height: 34px;
background: #cfcdcd;
color: #fff;
position: absolute;
left: 1px;
top: 1px;
text-align: center;
line-height: 34px;
font-size: 18px;
}
input {
padding-left: 44px;
border: 1px solid #cfcdcd;
height: 36px;
line-height: 36px;
width: 100%;
&.error {
border-color: $priceColor;
}
&.active,
&:focus {
border-color: $xtxColor;
}
}
.code {
position: absolute;
right: 1px;
top: 1px;
text-align: center;
line-height: 34px;
font-size: 14px;
background: #f5f5f5;
color: #666;
width: 90px;
height: 34px;
cursor: pointer;
}
}
>.error {
position: absolute;
font-size: 12px;
line-height: 28px;
color: $priceColor;
i {
font-size: 14px;
margin-right: 2px;
}
}
}
.agree {
a {
color: #069;
}
}
.btn {
display: block;
width: 100%;
height: 40px;
color: #fff;
text-align: center;
line-height: 40px;
background: $xtxColor;
&.disabled {
background: #cfcdcd;
}
}
}
.action {
padding: 20px 40px;
display: flex;
justify-content: space-between;
align-items: center;
.url {
a {
color: #999;
margin-left: 10px;
}
}
}
}
.subBtn {
background: $xtxColor;
width: 100%;
color: #fff;
}
</style>
配置路由跳轉(zhuǎn)
修改 src\views\Layout\components\LayoutNav.vue 文件中【請(qǐng)先登錄】的 a 標(biāo)簽:
<li><a href="javascript:;" @click="router.push('/login')">請(qǐng)先登錄</a></li>
表單校驗(yàn)實(shí)現(xiàn)
作用:前端提前校驗(yàn)可以省去一些錯(cuò)誤的請(qǐng)求提交,為后端節(jié)省接口壓力。
ElementPlus 表單組件內(nèi)置了表單校驗(yàn)功能,只需要按照組件要求配置必要參數(shù)即可(直接看文檔)。ElementPlus表單組件內(nèi)置了初始的校驗(yàn)配置,應(yīng)付簡(jiǎn)單的校驗(yàn)只需要通過配置即可,如果想要定制一些特殊的校驗(yàn)需求,可以使用自定義校驗(yàn)規(guī)則。
校驗(yàn)要求
用戶名:不能為空,字段名為 account
密碼:不能為空且為6-14個(gè)字符,字段名為 password
同意協(xié)議:必選,字段名為 agree
代碼實(shí)現(xiàn)
-
按照字段準(zhǔn)備表單對(duì)象:
// 1.準(zhǔn)備表單對(duì)象 const form = ref({ account: '', password: '', agree: true })
-
按照產(chǎn)品要求準(zhǔn)備規(guī)則對(duì)象:
// 2. 校驗(yàn)規(guī)則對(duì)象 const rules = { account: [ { required: true, message: '用戶名不能為空', trigger: 'blur' } ], password: [ { required: true, message: '密碼不能為空', trigger: 'blur' }, { min: 6, max: 24, message: '密碼長(zhǎng)度要求6-14個(gè)字符', trigger: 'blur' } ], agree: [ { validator: (rule, value, callBack) => { console.log(value) //自定義校驗(yàn)邏輯 // 勾選協(xié)議通過,不勾選不通過 if (value) { callBack() } else { callBack(new Error('請(qǐng)勾選協(xié)議')) } } } ] }
-
給表單綁定用戶表單對(duì)象和校驗(yàn)規(guī)則:
<el-form label-position="right" :model="form" :rules="rules" label-width="60px" status-icon> ... </el-form>
-
指定表單域的校驗(yàn)字段名:
<el-form-item prop="account" label="賬戶"> <el-input /> </el-form-item> <el-form-item prop="password" label="密碼"> <el-input /> </el-form-item> <el-form-item prop="agree" label-width="22px"> <el-checkbox size="large"> 我已同意隱私條款和服務(wù)條款 </el-checkbox> </el-form-item>
-
把表單對(duì)象進(jìn)行雙向綁定:
<el-form-item prop="account" label="賬戶">
<el-input v-model="form.account"/>
</el-form-item>
<el-form-item prop="password" label="密碼">
<el-input v-model="form.password"/>
</el-form-item>
<el-form-item prop="agree" label-width="22px">
<el-checkbox size="large" v-model="form.agree">
我已同意隱私條款和服務(wù)條款
</el-checkbox>
</el-form-item>
統(tǒng)一校驗(yàn)
在點(diǎn)擊登錄時(shí)需要對(duì)所有需要校驗(yàn)的表單進(jìn)行統(tǒng)一校驗(yàn)。
-
獲取表單實(shí)例:
// 3.獲取 form 實(shí)例做統(tǒng)一校驗(yàn) const formRef = ref(null)
與表單進(jìn)行綁定:
<el-form ref="formRef" label-position="right" :model="form" :rules="rules" label-width="60px" status-icon> ... </el-form>
-
編寫登錄邏輯:
const doLogin = () => { // 調(diào)用實(shí)例方法 formRef.value.validate(async (valid) => { // valid: 所有表單都通過校驗(yàn) 才為true console.log(valid) // 以valid做為判斷條件 如果通過校驗(yàn)才執(zhí)行登錄邏輯 if (valid) { // TODO LOGIN } }) }
-
與登錄按鈕進(jìn)行綁定:
<el-button size="large" class="subBtn" @click="doLogin">點(diǎn)擊登錄</el-button>
登錄基礎(chǔ)業(yè)務(wù)實(shí)現(xiàn)
基礎(chǔ)思想
- 調(diào)用登錄接口獲取用戶信息
- 提示用戶當(dāng)前是否成功
- 跳轉(zhuǎn)到首頁
-
新建 src\apis\user.js 文件,編寫登錄 api:
//封裝所有和用戶相關(guān)的接口函數(shù) import http from '@/utils/http' export const loginApi = ({ account, password }) => { return http({ url: '/login', method: 'POST', data: { account, password } }) }
-
src\views\Login\index.vue 中完善登錄邏輯:
// 3.獲取 form 實(shí)例做統(tǒng)一校驗(yàn) const router = useRouter() const formRef = ref(null) const doLogin = () => { const { account, password } = form.value // 調(diào)用實(shí)例方法 formRef.value.validate(async (valid) => { // valid: 所有表單都通過校驗(yàn) 才為true console.log(valid) // 以valid做為判斷條件 如果通過校驗(yàn)才執(zhí)行登錄邏輯 if (valid) { // TODO LOGIN await loginAPI({ account, password }) // 1. 提示用戶 ElMessage({ type: 'success', message: '登錄成功' }) // 2. 跳轉(zhuǎn)首頁 router.replace({ path: '/' }) } }) }
統(tǒng)一錯(cuò)誤信息提示
在 src\utils\http.js 中的響應(yīng)攔截器中進(jìn)行處理:
// axios響應(yīng)式攔截器
http.interceptors.response.use(res => res.data, e => {
// 統(tǒng)一錯(cuò)誤提示
ElMessage({
type: 'warning',
message: e.response.data.message
})
return Promise.reject(e)
})
Pinia 管理用戶數(shù)據(jù)
由于用戶數(shù)據(jù)的特殊性,在很多組件中都有可能進(jìn)行共享,共享的數(shù)據(jù)使用 Pinia 管理會(huì)更加方便。Pinia 負(fù)責(zé)用戶數(shù)據(jù)相關(guān)的 state 和 action,組件中只負(fù)責(zé)觸發(fā) action 函數(shù)并傳遞參數(shù)。
-
添加 src\stores\user.js 文件,在其中添加保存用戶數(shù)據(jù)的方法:
// 管理用戶數(shù)據(jù)相關(guān) import { defineStore } from 'pinia' import { ref } from 'vue' import { loginAPI } from '@/apis/user' export const useUserStore = defineStore('user', () => { // 1. 定義管理用戶數(shù)據(jù)的state const userInfo = ref({}) // 2. 定義獲取接口數(shù)據(jù)的action函數(shù) const getUserInfo = async ({ account, password }) => { const res = await loginAPI({ account, password }) userInfo.value = res.result } // 3. 以對(duì)象的格式把state和action return return { userInfo, getUserInfo } })
-
替換 src\views\Login\index.vue 中登錄邏輯的原代碼:
import {useUserStore} from '@/stores/user' ... const userStore = useUserStore() // TODO LOGIN await userStore.getUserInfo({ account, password })
Pinia 用戶數(shù)據(jù)持久化
用戶數(shù)據(jù)中有一個(gè)關(guān)鍵的數(shù)據(jù)叫做 Token(用來標(biāo)識(shí)當(dāng)前用戶是否登錄),而 Token 持續(xù)一段時(shí)間才會(huì)過期。Pinia 的存儲(chǔ)是基于內(nèi)存的,刷新就丟失,為了保持登錄狀態(tài)就要做到刷新不丟失,需要配合持久化進(jìn)行存儲(chǔ)。
最終效果:操作 state 時(shí)會(huì)自動(dòng)把用戶數(shù)據(jù)在本地的 localStorage 也存一份,刷新的時(shí)候會(huì)從 localStorage 中先取。
-
安裝 pinia 持久化插件 persistedstate:
npm i pinia-plugin-persistedstate
-
在 main.js 中注冊(cè) pinia 持久化插件:
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const app = createApp(App) const pinia = createPinia() //注冊(cè)持久化插件 pinia.use(piniaPluginPersistedstate) app.use(pinia)
-
對(duì) store 持久化配置:
export const useUserStore = defineStore('user', () => { ... }, { persist: true })
用戶登錄狀態(tài)
在首頁根據(jù)用戶登錄狀態(tài)區(qū)分顯示的模塊。
在 src\views\Layout\components\LayoutNav.vue 中獲取 pinia 中存儲(chǔ)的用戶數(shù)據(jù):
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
修改模板的 v-if 判斷邏輯:
<!--多模版渲染區(qū)分登錄狀態(tài)和非登錄狀態(tài)-->
<!--適配思路:登錄時(shí)顯示第一塊非登錄時(shí)顯示第二塊是否有token-->
<template v-if="userStore.userInfo.token">
<li><a href="javascript:;"><i class=" iconfont icon-user"></i>{{userStore.userInfo.account}}</a></li>
...
</template>
<template v-else>
...
</template>
請(qǐng)求攔截器攜帶 token
Token作為用戶標(biāo)識(shí),在很多個(gè)接口中都需要攜帶Token才可以正確獲取數(shù)據(jù),所以需要在接口調(diào)用時(shí)攜帶Token。另外,為了統(tǒng)一控制采取請(qǐng)求攔截器攜帶的方案。
Axiosi請(qǐng)求攔截器可以在接口正式發(fā)起之前對(duì)請(qǐng)求參數(shù)做一些事情,通常Token數(shù)據(jù)會(huì)被注入到請(qǐng)求header中,格式按
照后端要求的格式進(jìn)行拼接處理。格式如圖:
修改 src\utils\http.js 文件中的請(qǐng)求攔截器,從 pinia 獲取token數(shù)據(jù),將 token 存儲(chǔ)到請(qǐng)求的請(qǐng)求頭中:
// axios請(qǐng)求攔截器
htpp.interceptors.request.use(config => {
// 1. 從pinia獲取token數(shù)據(jù)
const userStore = useUserStore()
// 2. 按照后端的要求拼接token數(shù)據(jù)
const token = userStore.userInfo.token
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
}, e => Promise.reject(e))
退出登錄實(shí)現(xiàn)
基礎(chǔ)思想:
- 清除用戶信息
- 跳轉(zhuǎn)到登錄頁
-
src\stores\user.js 中新增清除用戶信息方法:
export const useUserStore = defineStore('user', () => { ... // 退出時(shí)清除用戶信息 const clearUserInfo = () => { userInfo.value = {} } // 3. 以對(duì)象的格式把state和action return return { userInfo, getUserInfo, clearUserInfo } }, { persist: true })
-
執(zhí)行退出邏輯,清除用戶信息:
<script setup> import { useUserStore } from '@/stores/userStore' import { useRouter } from 'vue-router' const userStore = useUserStore() const router = useRouter() const confirm = () => { console.log('用戶要退出登錄了') // 退出登錄業(yè)務(wù)邏輯實(shí)現(xiàn) // 1.清除用戶信息 觸發(fā)action userStore.clearUserInfo() // 2.跳轉(zhuǎn)到登錄頁 router.push('/login') } </script>
Token 失效攔截處理
Token的有效性可以保持一定時(shí)間,如果用戶一段時(shí)間不做任何操作,Token.就會(huì)失效,使用失效的Token再去請(qǐng)求一
些接口,接口就會(huì)報(bào)401狀態(tài)碼錯(cuò)誤,需要我們做額外處理。文章來源:http://www.zghlxwxcb.cn/news/detail-499754.html
在 src\utils\http.js 中進(jìn)行處理:文章來源地址http://www.zghlxwxcb.cn/news/detail-499754.html
// axios響應(yīng)式攔截器
http.interceptors.response.use(res => res.data, e => {
// 從pinia獲取token數(shù)據(jù)
const userStore = useUserStore()
// 統(tǒng)一錯(cuò)誤提示
ElMessage({
type: 'warning',
message: e.response.data.message
})
// 401 token 失效處理
// 1.清楚本地用戶數(shù)據(jù)
// 2.跳轉(zhuǎn)登錄頁
if(e.response.status===401){
userStore.clearUserInfo()
router.push('/login')
}
return Promise.reject(e)
})
到了這里,關(guān)于黑馬程序員前端 Vue3 小兔鮮電商項(xiàng)目——(八)登錄頁面的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!