1. 程式人生 > >vue開發:生成token儲存在客戶端localStorage中

vue開發:生成token儲存在客戶端localStorage中

前面我們已經瞭解了可以通過localStorage在客戶端(瀏覽器)儲存資料。

回顧token

框架中的RESTful api快速領悟(中):token認證 
框架中的RESTful api快速領悟(下):token的設定

我們後端有這樣一個介面:

http://localhost/yiiserver/web/index.php/token?client_appid=aaa&client_appkey=bbb 
  • 1
  • 1

其實就向clients(理解為使用者表即可)裡面去生成一個token 
這裡寫圖片描述

這裡寫圖片描述 
這裡的client_appid

 就相當於使用者名稱,client_appkey 就相當於密碼。 
這樣後端認證之後會生成一個access-token,我們需要把這個access-token 儲存在客戶端。

注意:我們前端一般部署在另外的伺服器上,會跨域,後端要處理跨域的問題,在PHP中可以寫上如下程式碼:

//指定允許其他域名訪問
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST");
header('Access-Control-Allow-Headers: X-Requested-With,content-type,if-modified-since'
)
;
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

前端的套路

注意,我們專案既然早已用上了VueX,那麼我肯定就要在Store(vuex裡的概念)裡面來建立一個module。 
這裡寫圖片描述

我們新建了一個UsersModule.js 來處理使用者登入的業務,注意不要忘記在入口檔案users-index.js 中引入。如果我們的『會員後臺』也需要使用者相關資料,也要引入。 
users-index.js 裡修改:

//引入模組
import ResModule from './../Store/modules/ResModules'
; import UsersModule from "./../Store/modules/UsersModule"; const vuex_config = new Vuex.Store({ modules: { res:ResModule, users:UsersModule } });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

1、UsersModule.js

import Vue from "vue";

export default {
    state:{
        currentUser:{
            get UserName(){
                return localStorage.getItem("currentUser_name");
            },
            get UserToken(){
                return localStorage.getItem("currentUser_token");
            }
        }
    },
    mutations:{
        setUser(state,{user_name,user_token}){
            // 在這裡把使用者名稱和token儲存起來
            localStorage.setItem("currentUser_name",user_name);
            localStorage.setItem("currentUser_token",user_token);
        }
    },
    actions:{
        userLogin(context,{user_name,user_pass}){
            // 傳送get請求做許可權認證(真實開發建議用post的方式)
            let url = "http://localhost/yiiserver/web/index.php/token?client_appid="+user_name+"&client_appkey="+user_pass;
            console.log(url);

            Vue.http.get(url)
                .then((res)=>{
                    if (res!=null && res.body!=undefined && "access-token" in res.body){
                        var token = res.body["access-token"];
                        if (token != ""){
                            // 後端API驗證通過
                            // 呼叫上面mutations裡定義的方法
                            context.commit("setUser",{"user_name":user_name,"user_token":token});
                        }
                    }else{
                        alert("使用者名稱密碼錯誤");
                    }
                },(res)=>{
                    alert("請求失敗進入這裡")
                });
        }
    }
}
  • 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
  • 40
  • 41
  • 42
  • 43
  • 44
  • 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
  • 40
  • 41
  • 42
  • 43
  • 44

actions部分:我們寫了一個userLogin()方法,來發送http請求後端伺服器,請求成功返回的資料呼叫在mutations部分定義的setUser()方法儲存到客戶端。 
注意:actions裡的userLogin()方法,是供在使用者登入頁呼叫的,也就是userslogin.vue裡。 
所以來到userlogin.vue,修改如下程式碼:

        methods:{
            login(){

                // 這個驗證是element-ui框架提供的方法
                this.$refs["users"].validate(function (flag) {
                    if(flag){
                        /*localStorage.setItem("currentUser",this.UserModel.user_name);
                        alert("使用者登入成功");*/

                        this.$store.dispatch("userLogin",{"user_name":this.UserModel.user_name,"user_pass":this.UserModel.user_pass})
                    }else{
                        alert("使用者名稱密碼必填");
                    }
                }.bind(this));
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

我們來測試一下,有沒有成功儲存到客戶端的localStorage 中: 
這裡寫圖片描述

2、如果我們的會員後臺 
http://localhost:8080/member 
也需要獲取使用者的登入資訊,比如使用者名稱。來顯示到導航欄上。

首先是應該在會員後臺模組的入口檔案member-index.js中:

//引入Module
import ResModule from './../Store/modules/ResModules';
import UsersMoule from "./../Store/modules/UsersModule";
const vuex_config = new Vuex.Store({
    modules: {
        res:ResModule,
        users:UsersMoule
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

然後我們就可以在,比如導航欄元件navbar.vue中:

<a href="##">{{this.$store.state.users.currentUser.UserName}}</a>
  • 1
  • 1

通過這樣的方式,訪問users裡的屬性。 
這裡寫圖片描述