1. 程式人生 > >localstorage 那些事 +vue記住密碼例項

localstorage 那些事 +vue記住密碼例項

localStorage.

然後就彈出了一些列宿主(瀏覽器)提供的localStorage自帶的方法,摘錄了一些常用的API如下表所示:

名稱作用
clear清空localStorage上儲存的資料
getItem讀取資料
hasOwnProperty檢查localStorage上是否儲存了變數x,需要傳入x
key讀取第i個數據的名字或稱為鍵值(從0開始計數)
lengthlocalStorage儲存變數的個數
propertyIsEnumerable用來檢測屬性是否屬於某個物件的
removeItem刪除某個具體變數
setItem儲存資料
toLocaleString將(陣列)轉為本地字串
valueOf獲取所有儲存的資料

清空localStorage

localStorage.clear()    // undefined    
localStorage            // Storage {length: 0}

儲存資料

localStorage.setItem("name","caibin") //儲存名字為name值為caibin的變數
localStorage.name = "caibin"; // 等價於上面的命令
localStorage // Storage {name: "caibin", length: 1}

讀取資料

localStorage.getItem("name") //caibin,讀取儲存在localStorage物件里名為name的變數的值
localStorage.name // "caibin" localStorage.valueOf() //讀取儲存在localStorage上的所有資料 localStorage.key(0) // 讀取第一條資料的變數名(鍵值) //遍歷並輸出localStorage裡儲存的名字和值 for(var i=0; i<localStorage.length;i++){ console.log('localStorage裡儲存的第'+i+'條資料的名字為:'+localStorage.key(i)+',值為:'+localStorage.getItem(localStorage.key(i))); }

刪除某個變數

localStorage.removeItem("name"); //undefined
localStorage // Storage {length: 0} 可以看到之前儲存的name變數已經從localStorage裡刪除了

檢查localStorage裡是否儲存某個變數

// 這些資料都是測試的,是在我當下環境裡的,只是demo哦~
localStorage.hasOwnProperty('name') // true
localStorage.hasOwnProperty('sex')  // false

將陣列轉為本地字串

var arr = ['aa','bb','cc']; // ["aa","bb","cc"]
localStorage.arr = arr //["aa","bb","cc"]
localStorage.arr.toLocaleString(); // "aa,bb,cc"

將JSON儲存到localStorage裡

var students = {
    xiaomin: {
        name: "xiaoming",
        grade: 1
    },
    teemo: {
        name: "teemo",
        grade: 3
    }
}

students = JSON.stringify(students);  //將JSON轉為字串存到變數裡
console.log(students);
localStorage.setItem("students",students);//將變數存到localStorage裡

var newStudents = localStorage.getItem("students");
newStudents = JSON.parse(students); //轉為JSON
console.log(newStudents); // 打印出原先物件
例子:
獲取儲存值:
getlocaluser(locuser,locpwd){//獲取localstroage儲存的使用者名稱密碼
    this.sel=false;   
    this.username = localStorage.getItem(locuser)
            this.password = localStorage.getItem(locpwd)           
            if(localStorage.getItem(locuser)&&localStorage.getItem(locpwd)){
            this.sel=true;
            }
    }
設定儲存值:
if(this.sel){  //設定要記住的賬戶,密碼
                                    localStorage.setItem("user",that.username)
                                    localStorage.setItem("pwd",that.password)
                                    }else{
                                    localStorage.removeItem("user");
                                    localStorage.removeItem("pwd");
                                    }

其中變數自行了斷~~~