模版
<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="/">
进入网站首页
<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">
我已同意隐私条款和服务条款
</el-checkbox>
</el-form-item>
<el-button size="large" class="subBtn">点击登录</el-button>
</el-form>
</div>
</div>
</div>
</section>
<footer class="login-footer">
<div class="container">
<p>
<a href="javascript:;">关于我们</a>
<a href="javascript:;">帮助中心</a>
<a href="javascript:;">售后服务</a>
<a href="javascript:;">配送与验收</a>
<a href="javascript:;">商务合作</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>
配置路由
// createRouter:创建router实例对象
// createWebHistory:创建history模式的路由
import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import Home from '@/views/Home/index.vue'
import Category from '@/views/Category/index.vue'
import SubCategory from '@/views/SubCategory/index.vue'
import Detail from '@/views/Detail/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
// path和component对应关系的位置
routes: [
{
path: '/',
component: Layout,
children: [
{
path: '',
component: Home
},
{
path: 'category/:id',
component: Category
},
{
path: 'category/sub/:id',
component: SubCategory
},
{
path: 'detail/:id',
component: Detail
}
]
},
{
path: '/login',
component: Login
}
],
// 路由滚动行为定制
scrollBehavior () {
return {
top: 0
}
}
})
export default router
配置路由跳转
<li><a href="javascript:;" @click="router.push('/login')">请先登录</a></li>
<script setup>
import { ref } from 'vue'
// 表单数据对象
const userInfo = ref({
account: '1311111111',
password: '123456',
agree: true
})
// 规则数据对象
const rules = {
account: [
{ required: true, message: '用户名不能为空' }
],
password: [
{ required: true, message: '密码不能为空' },
{ min: 6, max: 14, message: '密码长度要求6-14个字符' }
],
agree: [
{
validator: (rule, val, callback) => {
//value当初输入的值
//callback校验处理函数
return val ? callback() : new Error('请先同意协议')
}
}
]
}
</script>
<template>
<div class="form">
<el-form ref="formRef" :model="userInfo" :rules="rules" status-icon>
<el-form-item prop="account" label="账户">
<el-input v-model="userInfo.account" />
</el-form-item>
<el-form-item prop="password" label="密码">
<el-input v-model="userInfo.password" />
</el-form-item>
<el-form-item prop="agree" label-width="22px">
<el-checkbox v-model="userInfo.agree" size="large">
我已同意隐私条款和服务条款
</el-checkbox>
</el-form-item>
<el-button size="large" class="subBtn" @click='doLogin' >点击登录</el-button>
</el-form>
</div>
</template>
思考:每个表单域都有自己的校验触发事件,如果用户一上来就点击登陆怎么办呢?
在点击登陆时需要对所有需要校验的表单进行统一校验
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import 'element-plus/theme-chalk/el-message.css'
import { useRouter } from 'vue-router'
const formRef = ref(null)
const router = useRouter()
const doLogin = () => {
const { account, password } = form.value
// 调用实例方法
formRef.value.validate(async (valid) => {
// valid: 所有表单都通过校验 才为true
console.log(valid)
// 以valid做为判断条件 如果通过校验才执行登录逻辑
if (valid) {
// TODO LOGIN
await loginAPI({ account, password })
// 1. 提示用户
ElMessage({ type: 'success', message: '登录成功' })
// 2. 跳转首页
router.replace({ path: '/' })
}
})
}
为什么要用Pinia管理数据
由于用户数据的特殊性,在很多组件中都有可能进行共享,共享的数据使用pinia管理会更加方便
如何使用pinia管理数据
遵循理念:和数据相关的所有操作(state+action)都放到Pinia中,组件只负责触发action函数
stores/user.js
// 管理用户数据相关
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
export const useUserStore = defineStore('user', () => {
// 1. 定义管理用户数据的state
const userInfo = ref({})
// 2. 定义获取接口数据的action函数
const getUserInfo = async ({ account, password }) => {
const res = await loginAPI({ account, password })
userInfo.value = res.result
}
// 3. 以对象的格式把state和action return
return {
userInfo,
getUserInfo
}
}, {
persist: true,
})
login.vue
import { useUserStore } from '@/stores/userStore'
const userStore = useUserStore()
// TODO LOGIN
await userStore.getUserInfo({ account, password })
持久化用户数据说明
1️⃣用户数据中有一个关键的数据叫做token(用来标识当前用户是否登陆),而token持续一段时间才会过期
2️⃣Pinia的存储是基于内存,刷新就丢失,为了保持登陆状态就要做到刷新不丢失,需要配合持久话进行存储
实现效果
操作state时自动把用户数据在本地的localStorege也存一份,刷新的时候会从localStorege中先取出
运行机制
在设置state的时候会自动把数据同步给localstorage,在获取state数据的时候会优先从localstorage中取
pinia-plugin-persistedstate适用于pinia的持久化存储插件
https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/
安装
npm i pinia-plugin-persistedstate
main.js注册
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
stores/user.js
import { defineStore } from 'pinia'
export const useStore = defineStore(
'main',
() => {
},
{
//持久化配置
persist: true,
},
)
多模版适配的通用思路
思路:有几个需要适配的模版就准备几个template片段,通过条件渲染控制显示
<script setup>
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
</script>
<template>
<nav class="app-topnav">
<div class="container">
<ul>
<!-- 多模版渲染 区分登录状态和非登录状态 -->
<!-- 适配思路: 登录时显示第一块 非登录时显示第二块 是否有token -->
<template v-if="userStore.userInfo.token">
<li><a href="javascript:;"><i class=" iconfont icon-user"></i>{{ userStore.userInfo.account }}</a></li>
<li>
<el-popconfirm @confirm="confirm" title="确认退出吗?" confirm-button-text="确认" cancel-button-text="取消">
<template #reference>
<a href="javascript:;">退出登录</a>
</template>
</el-popconfirm>
</li>
<li><a href="javascript:;">我的订单</a></li>
<li><a href="javascript:;">会员中心</a></li>
</template>
<template v-else>
<li><a href="javascript:;" @click="$router.push('/login')">请先登录</a></li>
<li><a href="javascript:;">帮助中心</a></li>
<li><a href="javascript:;">关于我们</a></li>
</template>
</ul>
</div>
</nav>
</template>
<style scoped lang="scss">
.app-topnav {
background: #333;
ul {
display: flex;
height: 53px;
justify-content: flex-end;
align-items: center;
li {
a {
padding: 0 15px;
color: #cdcdcd;
line-height: 1;
display: inline-block;
i {
font-size: 14px;
margin-right: 2px;
}
&:hover {
color: $xtxColor;
}
}
~li {
a {
border-left: 2px solid #666;
}
}
}
}
}
</style>
token作为用户标识,在很多个接口中都需要携带token才可以正确获取数据,所以需要在接口调用携带token,另外,为了统一控制采取请求拦截器携带的方案
如何配置
Axios请求拦截可以在接口正式发起之前对请求参数做一些事情,通常token数据会被注入到请求header中,格式按照后端要求的格式进行拼接处理
// axios请求拦截器
import { useUserStore } from '@/stores/userStore'
httpInstance.interceptors.request.use(config => {
// 1. 从pinia获取token数据
const userStore = useUserStore()
// 2. 按照后端的要求拼接token数据
const token = userStore.userInfo.token
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
}, e => Promise.reject(e))
// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
// 统一错误提示
ElMessage({
type: 'warning',
message: e.response.data.message
})
return Promise.reject(e)
})
script setup>
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
const confirm = () => {
console.log('用户要退出登录了')
// 退出登录业务逻辑实现
// 1.清除用户信息 触发action
userStore.clearUserInfo()
// 2.跳转到登录页
router.push('/login')
}
</script>
<el-popconfirm @confirm="confirm" title="确认退出吗?" confirm-button-text="确认" cancel-button-text="取消">
<template #reference>
<a href="javascript:;">退出登录</a>
</template>
</el-popconfirm>
stores/userStore
// 退出时清除用户信息
const clearUserInfo = () => {
userInfo.value = {}
// 执行清除购物车的action
cartStore.clearCart()
}
token的有效性可以保持一定时间,如果用户一段时间不做任何操作,token就会失效,使用失效的token再去请求一些接口,接口就会报401状态码错误,需要我们做额外处理
// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
// 统一错误提示
ElMessage({
type: 'warning',
message: e.response.data.message
})
return Promise.reject(e)
})
//401token失效处理
//1.清除本地用户数据
//2.跳转到登陆页
if(e.response.status===401){
userStore.clearUserInfo()
router.push('/login')
}