效果圖:
1、首先來根據Element網站實現布局:
<template> <div class="login_container"> <div class="login_box"> <!--頭像區域--> <div class="avatar_box"> <img src="../assets/logo.png" alt /> </div> <!--表單區域--> <el-form label-width="0px" class="login_form"> <el-form-item> <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input> </el-form-item> <el-form-item> <el-input prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" show-password></el-input> </el-form-item> <el-form-item class="btns"> <el-button type="primary">登錄</el-button> <el-button type="info">重置</el-button> </el-form-item> </el-form> </div> </div> </template> <script> export default { data () { return { // 登錄表單的數據綁定對象 loginForm: { username: '', password: '' }, } } </script> <style lang="less" scoped> .login_container { height: 100%; background: #2b4b6b; } .login_box { width: 450px; height: 300px; background: #fff; border-radius: 3px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); .avatar_box { padding: 10px; width: 130px; height: 130; border: 1px solid #eee; border-radius: 50%; box-shadow: 0 0 10px #ddd; position: absolute; left: 50%; transform: translate(-50%, -50%); background: #fff; img { width: 100%; height: 100%; border-radius: 50%; background: #eee; } } } .login_form { position: absolute; bottom: 0; width: 100%; padding: 0 20px; box-sizing: border-box; } .btns { display: flex; justify-content: flex-end; } </style>
2、加入表單驗證規則
加入 :rules="loginFormRules"
<el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form"> <el-form-item prop="username"> <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input> </el-form-item> <el-form-item prop="password"> <el-input prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" show-password></el-input> </el-form-item> <el-form-item class="btns"> <el-button type="primary">登錄</el-button> <el-button type="info">重置</el-button> </el-form-item> </el-form> <script> export default { data () { return { // 登錄表單的數據綁定對象 loginForm: { username: '', password: '' }, // 表單的驗證規則對象 loginFormRules: { username: [ { required: true, message: '請輸入登錄名稱', trigger: 'blur' }, { min: 3, max: 10, message: '長度在 3 到 10 個字符', trigger: 'blur' } ], password: [ { required: true, message: '請輸入登錄密碼', trigger: 'blur' }, { min: 6, max: 15, message: '長度在 6 到 15 個字符', trigger: 'blur' } ] } } } } </script>
3、重置按鈕
resetFields 對整個表單進行重置,將所有字段值重置為初始值並移除校驗結果
加入ref="loginFormRef"和@click="resetLoginForm"
<el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form"> <el-form-item prop="username"> <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input> </el-form-item> <el-form-item prop="password"> <el-input prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" show-password></el-input> </el-form-item> <el-form-item class="btns"> <el-button type="primary">登錄</el-button> <el-button type="info" @click="resetLoginForm">重置</el-button> </el-form-item> </el-form> <script> export default { data () { return { // 登錄表單的數據綁定對象 loginForm: { username: '', password: '' }, // 表單的驗證規則對象 loginFormRules: { username: [ { required: true, message: '請輸入登錄名稱', trigger: 'blur' }, { min: 3, max: 10, message: '長度在 3 到 10 個字符', trigger: 'blur' } ], password: [ { required: true, message: '請輸入登錄密碼', trigger: 'blur' }, { min: 6, max: 15, message: '長度在 6 到 15 個字符', trigger: 'blur' } ] } } }, methods: { // 點擊重置按鈕 重置表單 resetLoginForm () { // console.log(this) this.$refs.loginFormRef.resetFields() } } } </script>
4、登錄前的預校驗:
validate
說明:對整個表單進行校驗的方法,參數為一個回調函數。該回調函數會在校驗結束后被調用,並傳入兩個參數:是否校驗成功和未通過校驗的字段。若不傳入回調函數,則會返回一個promise
參數:Function(callback: Function(boolean, object))
<el-button type="primary" @click="submitLogin">登錄</el-button> <script> export default { methods: { // 點擊登錄按鈕 submitLogin () { this.$refs.loginFormRef.validate(valid => { console.log(valid) }) }, // 點擊重置按鈕 重置表單 resetLoginForm () { // console.log(this) this.$refs.loginFormRef.resetFields() } } } </script>
5、通過axios發起請求:
可以先進行配置 main.js
import axios from 'axios' // 配置請求的根路徑 axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/' Vue.prototype.$http = axios
頁面調用:
// 點擊登錄按鈕 submitLogin () { this.$refs.loginFormRef.validate(async valid => { // console.log(valid) if (!valid) return const { data: res } = await this.$http.post('login', this.loginForm) // console.log(res) if (res.meta.status !== 200) return console.log('登錄失敗') console.log('登錄成功') }) },
6、配置彈框提示
打開plugins/element.js
import Vue from 'vue' import { Button, Form, FormItem, Input, Message } from 'element-ui' Vue.use(Button) Vue.use(Form) Vue.use(FormItem) Vue.use(Input) // 掛載到Vue全局 Vue.prototype.$message = Message
修改Login.vue代碼
// 點擊登錄按鈕 submitLogin () { this.$refs.loginFormRef.validate(async valid => { // console.log(valid) if (!valid) return const { data: res } = await this.$http.post('login', this.loginForm) // data重定向為res // console.log(res) if (res.meta.status !== 200) return this.$message.error('登錄失敗') this.$message.success('登錄成功') }) },

7、登錄之后的token保存到客戶端的sessionStorage中
項目中除了登錄之外的其他api接口,必須在登錄之后才能訪問
token只在當前網站打開期間生效,所以將token保存在sessionStorage中
// 點擊登錄按鈕 submitLogin () { this.$refs.loginFormRef.validate(async valid => { // console.log(valid) if (!valid) return const { data: res } = await this.$http.post('login', this.loginForm) // data重定向為res // console.log(res) if (res.meta.status !== 200) return this.$message.error('登錄失敗') this.$message.success('登錄成功') // 將登錄成功之后的token保存到客戶端的sessionStorage中 window.sessionStorage.setItem('token', res.data.token) })
8、通過編程式導航跳轉到后台主頁,路由地址是 /home
修改Login.vue:
// 點擊登錄按鈕 submitLogin () { this.$refs.loginFormRef.validate(async valid => { // console.log(valid) if (!valid) return const { data: res } = await this.$http.post('login', this.loginForm) // data重定向為res // console.log(res) if (res.meta.status !== 200) return this.$message.error('登錄失敗') this.$message.success('登錄成功') // 將登錄成功之后的token保存到客戶端的sessionStorage中 window.sessionStorage.setItem('token', res.data.token) // 通過編程式導航跳轉到后台主頁,路由地址是 /home this.$router.push('/home') }) }
新建home路由:
import Home from '../components/Home.vue' const routes = [ { path: '/', redirect: '/login' }, // 重定向 { path: '/login', component: Login }, { path: '/home', component: Home } ]
新建Home.vue文件:
<template> <div class=""> Home組件 </div> </template> <script> export default { } </script> <style lang="less" scoped> </style>

9、Home頁增加訪問權限
現在把Session Storage清空,刷新Home頁還是能訪問的,而我們的需求是:如果用戶沒有登錄,但是直接通過URL訪問特定權限的頁面,需要重新導航到登錄頁面。
beforEach路由導航守衛:
- to:router即將進入的路由對象。
- from:當前導航正要離開的路由。
- next:一個function,一定要調用該方法來 resolve 這個鈎子。執行效果依賴 next 方法的調用參數。
- next() : 進行管道中的下一個鈎子。如果全部鈎子執行完了,則導航的狀態就是 confirmed (確認的)。
- next(false) : 中斷當前的導航。如果瀏覽器的 URL 改變了(可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應的地址。
- next('/') 或者 next({ path: '/' }): 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。 你可以向 next 傳遞任意位置對象,且允許設置諸如 replace: true、name: ‘home' 之類的選項以及任何用在 router-link 的 to prop 或 router.push 中的選項,注意,next可以通過query傳遞參數。
- next(error) : (2.4.0+) 如果傳入 next 的參數是一個 Error 實例,則導航會被終止且該錯誤會被傳遞給 router.onError() 注冊過的回調。
在router里添加路由守衛:
// 掛載路由導航守衛 router.beforeEach((to, from, next) => { // to:將要訪問的路徑 // from:代表從那個路徑跳轉而來 // next是一個函數,表示放行; next() 放行 next('/login') 強制跳轉 // 如果用戶訪問的登錄頁,直接放行 if (to.path === '/login') return next() // 從sessionStorage中獲取到保存的token值 const tokenStr = window.sessionStorage.getItem('token') // 沒有token 強制跳轉到登錄頁 if (!tokenStr) return next('/login') next() })
現在在瀏覽器里輸入 http://localhost:8080/#/home 會 強制跳轉為 http://localhost:8080/#/login
10、退出功能
基於token的方式實現退出比較簡單,只需要銷毀本地的token即可。這樣,后續的請求就不會攜帶token,必須重新登錄生成一個新的token之后才可以訪問頁面
Home頁面里添加退出按鈕:
<el-button type="info" @click="logout">退出</el-button> <script> export default { methods: { logout () { // 清空token window.sessionStorage.clear('token') // 跳轉到登錄頁 this.$router.push('/login') } } } </script>
OK,功能實現。
