Vue.js实现一个SPA登录页面的过程

时间:2022-05-04
本文章向大家介绍Vue.js实现一个SPA登录页面的过程,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

技术栈

  • vue.js 主框架
  • vuex 状态管理
  • vue-router 路由管理
  • 一般过程 在一般的登录过程中,一种前端方案是:
    1. 检查状态:进入页面时或者路由变化时检查是否有登录状态(保存在cookie或者本地存储的值);
    2. 如果有登录态则查询登录信息(uid,头像等...)并保存起来;如果没有则跳转到登录页;
    3. 在登录页面(或者登录框),校检用户输入信息是否合法;
    4. 校检通过后发送登录请求;校检不成功则反馈给用户;
    5. 登录成功则从后端数据中取出session信息保存登录状态(可能需要跳转);登录不成功则提示用户不成功;
    6. 用户做出注销操作时删除登录状态。

    下面我根据列出的步骤一一分析如何做代码实现,所有在代码在https://github.com/doterlin/vue-example-login中,并带有较详细注释帮助理解代码。 在此之前假设登录页面路由为/login,登录后的路由为/user_info。这样只需要在App.vue放好router-view用于存放和渲染这两个路由。

// component/App.vue
<template>
<div class="container" id="app">
 <transition name="fade">
 <keep-alive>
  <router-view></router-view>
 </keep-alive>
 </transition>
</div>
</template>
...
// js/app.js
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
 }]
})
...
// js/app.js
...
var app = new Vue({
 data: {},
 el: '#app',
 render: h => h(App),
 router,
 store,
 methods:{
 checkLogin(){
  //检查是否存在session
  //cookie操作方法在源码里有或者参考网上的即可
  if(!this.getCookie('session')){
  //如果没有登录状态则跳转到登录页
  this.$router.push('/login');
  }else{
  //否则跳转到登录后的页面
  this.$router.push('/user_info');
  }
 }
 }
})
// js/app.js
...
var app = new Vue({
 ...
 created() {
 this.checkLogin();
 },
 methods:{
 checkLogin(){
  ...
 }
 }
})
// js/app.js
...
var app = new Vue({
 ...
 //监听路由检查登录
 watch:{
 "$route" : 'checkLogin'
 },

 //进入页面时
 created() {
 this.checkLogin();
 },

 methods:{
 checkLogin(){
  ...
 }
 }
})
// component/App.vue
...
<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) => {
  //Success
  if(response.data.code == 0){
   this.$store.commit('updateUserInfo', this.userInfo); 
  }
  }, (response) => {
  //Error
  });
 
 }
 }
}
</script>
...
// js/app.js
// Vuex配置
...
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;
 }
 }
})
...
//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:;" rel="external nofollow" 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>
...
...
  //登录请求
  toLogin(){

   //一般要跟后端了解密码的加密规则
   //这里例子用的哈希算法来自./js/sha1.min.js
   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) => {
   //Error
   });
...
// component/UserInfo.vue
...
 logout(){
  //删除cookie并跳到登录页
  this.isLogouting = true;
  //请求后端,比如logout.php
  // this.$http.post('eaxmple.com/logout.php')...
  //成功后删除cookie
  this.delCookie('session');

  //重置loding状态
  this.isLogouting = false;

  //跳转到登录页
  this.$router.push('/login/');
 }
...