论如何用Vue写一个SPA登录页面的过程
SPA登录属于Vue项目实战的基础内容,整理一波开发心路历程
前言:技术栈
Vue + Vuex + Vue-router全家桶老生常谈了,这里不做多赘述
一般过程
在一般的登录过程中,一种前端方案是:
- 检查状态:进入页面时或者路由变化时检查是否有登录状态(保存在
cookie
或者本地存储
的值);
- 如果有登录态则查询登录信息(uid,头像等…)并保存起来;如果没有则跳转到登录页;
- 在登录页面(或者登录框),校检用户输入信息是否合法;
- 校检通过后发送登录请求;校检不成功则反馈给用户;
- 登录成功则从后端数据中取出
session
信息保存登录状态(可能需要跳转);登录不成功则提示用户不成功;
- 用户做出注销操作时删除登录状态。
在此之前假设登录页面路由为/login
,登录后的路由为/user_info
。这样只需要在App.vue
放好router-view
用于存放和渲染这两个路由。
1 2 3 4 5 6 7 8 9 10
| // component/App.vue <template> <div class="container" id="app"> <transition name="fade"> <keep-alive> <router-view></router-view> </keep-alive> </transition> </div> </template>
|
并做好vue-router
配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import Vue from 'vue' import VueRouter from 'vue-router' import Login from '../component/Login.vue' import UserInfo from '../component/UserInfo.vue'
Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: '/login', component: Login }, { path: '/user_info', component: UserInfo }] })
|
检查状态与跳转
在两个时候我们需要检查状态:
用户打开页面时
路由发生变化时
首先需要写好一个检查登录态的方法checkLogin
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| ... var app = new Vue({ data: {}, el: '#app', render: h => h(App), router, store, methods:{ checkLogin(){ if(!this.getCookie('session')){ this.$router.push('/login'); }else{ this.$router.push('/user_info'); } } } })
|
关于 render与 template 的主要区别,会在之后的内容继续阐述
为了提升用户体验,当用户打开页面时前端需要检查他是否已经登录,不需要用户再次登录。这个实现很简单,我们在vue实例
的created
钩子里写好:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| ... var app = new Vue({ ... created() { this.checkLogin(); }, methods:{ checkLogin(){ if(!this.getCookie('session')){ this.$router.push('/login'); }else{ this.$router.push('/user_info'); } } } })
|
另外,路由
发生变化时也需要检查登录,以下情景(路由变化)如果我们不检查登录态可能会发生错误:
- 用户在进入页面时存在登录状态,但在做操作时正好登录过期了;
- 用户手动删除了
cookie
/本地storage
并做操作;
- 用户在未登录的情况下手动输入(或者从收藏夹进入)某个需要登录的路由
- 用户在已登录的情况下进入登录页路由
这些足够成为我们监听路由的理由,实现的话可以利用vue
的watch
功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| ... var app = new Vue({ ... watch:{ "$route" : 'checkLogin' },
created() { this.checkLogin(); },
methods:{ checkLogin(){ if(!this.getCookie('session')){ this.$router.push('/login'); }else{ this.$router.push('/user_info'); } } } })
|
我们分别针对上面四种情况来进行分析:
操作过程中过期的情况,由于我们对checkLogin进行了watch操作,那么对于里面涉及到的数据发生了变化,就会重新进行checkLogin,所以就会执行push(‘/login’)这一操作,而对于其他三种情况原理都一样,都是通过watch来进行监听,随时进行检查,稍有不对劲就可以进行相对应的push操作。
至此,我们就完成了一般过程
中的第1步。接下来实现如何获取用户个人信息。
获取用户信息
在成功登录后,我们一般需要从后端显示用户的一些信息,比如昵称,头像,等级等等…获取的话很简单,发一个http请求从后端拉取;但是一般这些信息会在多的路由中被用到(比如uid一般都需要在各个后端接口中作为参数带上),所以需要保存到全局状态中(vuex
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| ... <script> export default { ... mounted(){ this.getUserInfo(); }, methods: { getUserInfo(){ this.userInfo = { nick: 'Doterlin', ulevel: 20, uid: '10000', portrait: 'images/profile.png' }
ts.$http.get(url, { "params": this.userInfo }).then((response) => { if(response.data.code == 0){ this.$store.commit('updateUserInfo', this.userInfo); } }, (response) => { });
} } } </script> ...
|
当然我们需要在之前配置好,比如在写在app.js
或者单独写成store.js
并在app.js
引入(推荐):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
... const store = new Vuex.Store({ state: { domain:'http://test.example.com', userInfo: { nick: null, ulevel: null, uid: null, portrait: null } }, mutations: { updateUserInfo(state, newUserInfo) { state.userInfo = newUserInfo; } } }) ...
|
输入校验和发送登录请求
为了防止一些不符合预期的字符和过于频繁的请求传到后台,前端要对用户的输入进行校验和防止重复请求。当然不同网站的合法字符不一样,这里只做为空
时不合法的校验:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| //component/Login.vue <template> <div class="login" id="login"> ... <div class="log-email"> <input type="text" placeholder="Email" :class="'log-input' + (account==''?' log-input-empty':'')" v-model="account"><input type="password" placeholder="Password" :class="'log-input' + (password==''?' log-input-empty':'')" v-model="password"> <a href="javascript:;" class="log-btn" @click="login">Login</a> </div> ... </div> </template> <script> import Loading from './Loading.vue' export default { name: 'Login', data(){ return { isLoging: false, account: '', password: '' } }, components:{ Loading }, methods:{
//登录逻辑 login(){ if(this.account!='' && this.password!=''){ this.toLogin(); } }
} </script> ...
|
这里的this.toLogin
就是登录请求的方法,在post
密码到后端时不是直接发送,一般会按照后端定的规则加密后在发送,比如哈希算法
,例子进行了的双重哈希加密,引用了js/sha1.min.js
,大致实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| ... toLogin(){
let password_sha = hex_sha1(hex_sha1( this.password ));
let loginParam = { account: this.account, password_sha }
this.isLoging = true; this.$http.post( 'example.com/login.php', { param: loginParam).then((response) => { if(response.data.code == 1){ let expireDays = 1000 * 60 * 60 * 24 * 15; this.setCookie('session', response.data.session, expireDays); this.$router.push('/user_info'); } }, (response) => { });
...
|
这样就完成了第3,4,5个步骤了。最后一步就是注销。
注销
注销时有的需要请求后端有的不需要,关键的事要删除保存的登录状态:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| ... logout(){ this.isLogouting = true; this.delCookie('session');
this.isLogouting = false;
this.$router.push('/login/'); } ...
|
这种登录方式是通过 cookie,除此之外还有session跟token两种主流方式,下次再言