1. 程式人生 > 程式設計 >VUE實現token登入驗證

VUE實現token登入驗證

本文例項為大家分享了實現token登入驗證的具體程式碼,供大家參考,具體內容如下

實現這個登入功能的過程真是一波三折,中途出現了bug,整了兩三天才解決了問題,心力交瘁,簡直一個頭兩個大,感覺自己的毅力和耐心又提升了一個層次。

好在最終在同學的幫助下解決了bug,不過我又再次感受到了作為一個菜鳥的淺薄,大佬的問題屢次觸及到我的知識盲區......現在詳細地記錄一下實現token登入驗證的步驟,以防以後再犯錯。

1.封裝store對token的操作方法

首先在src目錄下建立一個store資料夾,再建立一個main.檔案

VUE實現token登入驗證

main.js存放的程式碼作用是獲取token的值和用localStorage儲存、刪除本地token的值

import Vue from 'vue';
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
export default new VuKuymnwex.Store({
  state: {
    token: localStorage.getItem('token') ? localStorage.getItem('token') : ''
  },mutations: {
    setToken (state,token) {
      state.token =token;
      localStorage.setItem("token",token.token);     //儲存token
    },delToken (state) {
      state.token = '';
      localStorage.removeItem("token");    //刪除token
    }
  }
})

2.在頁面中連線登入介面進行驗證

登入

(1)輸入框程式碼

<input type="text" v-model="username" placeholder="使用者名稱" />
<input type="password" v-model="password" placeholder="密碼"/>

(2)script程式碼

<script>
  import { mapMutations } from 'vuex';
  export default {
    name: "managerLogin",data() {
      return {
        username:'',//使用者名稱
        password:'',//密碼
      };
    },methods:{
      ...mapMutations(['setToken']),login:function() {
        if (this.username === '' || this.password === '') {
          alert("賬號或密碼不能為空!");
        }
        else {
          //根據api介面獲取token
          this.$ajax.get('http:///api/wx/Public/login',{
            params: {      //傳入引數
              username: this.username,password: this.password,device_type: "mobile"
            }
          }).then(
            res => {
              console.log(res.data);
              if(res.data.code===1) {    //若code=1則驗證成功
                this.setToken({token: res.data.data.token});    //store中的為token賦值方法
                this.$router.push('/managerHome');
              }
              else{
                alert(res.data.msg);   //彈出錯誤資訊
              }
            }).catch(error => {
            alert('介面連線錯誤');
          www.cppcns.com
console.log(error); }); } } } </script>

退出登入

<script>
    import {mapMutations} from "vuex";
    export default {
      name: "manager_infor",methods:{
        ...mapMutations(['delToken']),exit:function(){
          this.delToken({token:''});
          this.$router.push('/managerLogin');
        }
      }
    }
</script>

3.路由守衛

這段程式碼放在路由檔案裡,作用是在頁面跳轉前通過檢視本地儲存的token值進行登入驗證來判斷是否跳轉

VUE實現token登入驗證

router.beforeEach((to,from,next) => {
  if (to.path === '/managerLogin') {    //若要跳轉的頁面是登入介面
    next();     //直接跳轉
  }
  else if (to.path === '/managerHome'){   //若要跳轉的頁面是個人介面
    let token = localStorage.getItem('token');    //獲取本地儲存的token值
    if (token===null||token===''){    //若token為空則驗證不成功,跳轉到登入頁面
 www.cppcns.com     next('/managerLogin');
    }
    else{           //不為空則驗證成功
      next();
    }
  }
  else{
    next();
  }
});
 
export default router;

4.axios請求攔截器

這段程式碼放在src檔案下的mian.js檔案裡

import axios from "axios";
import store from './store/main';
Vue.prototype.$ajax = axios
 
new Vue({
  el: '#app',router,store,//store要加進來
  components: { App },template: '<App/>'
})
 
//請求攔截器
axios.interceptors.request.use(config => {
//判斷是否存在token,如果存在將每個頁面的header都新增token
  if(store.state.token){
    
    config.headers.common['XX-Token']=store.state.token   //此處的XX-Token要根據登入介面中請求頭的名字來寫
  }
 
  return config;
},error => {
// 請求錯誤
  return Promise.reject(error);
});
 
//respone攔截器
axios.interceptors.response.use(
  response => {
    return response;
  },error => {  //預設除了2XX之外都為錯誤
    if(error.response){
      switch(error.response.status){
        case 401:
          this.$store.commit('delToken');
          router.replace({ //跳轉到登入頁面
            path: '/managerLogin',query: { redirect: router.currentRoute.fullPath } // 將跳轉的路由path作為引數,登入成功後跳轉到該路由
          });
      }
    }
   http://www.cppcns.com return Promise.reject(error.response);
  }
);

大功告成!

放上我的後端介面的資料結構作為參考,以上的程式碼使用不同的介面會有一些差異,要懂得靈活運用。

VUE實現token登入驗證

VUE實現token登入驗證

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。