Vue?瀏覽器本地存儲的問題小結(jié)
localstorage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>瀏覽器本地存儲</title> </head> <body> <div id="root"> <button onclick="saveData()">點我保存一個數(shù)據(jù)</button> <button onclick="readData()">點我讀取一個數(shù)據(jù)</button> <button onclick="deleteData()">點我刪除一個數(shù)據(jù)</button> <button onclick="deleteAllData()">點我清空數(shù)據(jù)</button> </div> <script type="text/javascript"> let person = {name:"張三",age:"18"} function saveData() { localStorage.setItem("msg","hello") localStorage.setItem("msg2",666) localStorage.setItem("msg3",JSON.stringify(person)) } function readData(){ console.log(localStorage.getItem("msg")) console.log(localStorage.getItem("msg2")) const result = localStorage.getItem("msg3") console.log(result) console.log(JSON.parse(result)) } function deleteData(){ localStorage.removeItem("msg") } function deleteAllData(){ localStorage.clear() } </script> </body> </html>
SessionStorage
和 LocalStorage 用法相同,把上邊代碼中的 localStorage
改為sessionStorage
總結(jié)
LocalStorage 和 SessionStorage 統(tǒng)稱為 WebStorage
1.存儲內(nèi)容大小一般支持5MB左右(不同瀏覽器可能還不一樣)
⒉瀏覽器端通過 Window.sessionStorage
和Window.localStorage
屬性來實現(xiàn)本地存儲機制
3.相關(guān)API:
1.xxxxxStorage.setItem( " key’ , “value”);
該方法接受一個鍵和值作為參數(shù),會把鍵值對添加到存儲中,如果鍵名存在,則更新其對應的值
2.xxxxxStorage.getItem( “person”);
該方法接受一個鍵名作為參數(shù),返回健名對應的值
3.xxxxxStorage.removeItem( “key”);
該方法接受一個鍵名作為參數(shù),并把該鍵名從存儲中刪除
4.xxxxxStorage.clear()
該方法會清空存儲中的所有數(shù)據(jù)
4.備注:
1.SessionStorage 存儲的內(nèi)容會隨著瀏覽器窗口關(guān)閉而消失2.LocalStorage 存儲的內(nèi)容,需要手動清除才會消失(調(diào)用api 或 清空緩存)
3. xxxxStorage.getItem(xxx),如果 xxx 對應的 value 獲取不到,那么 getltem 的返回值是null
4.JSON.parse(null) 的結(jié)果依然是 null
TodoList 改為本地存儲
我們之前寫的 TodoList 案例數(shù)據(jù)是寫死的,每次刷新都恢復到寫死的數(shù)據(jù),我們現(xiàn)在把它改為本地存儲。修改 App.vue,把 todos 改為深度監(jiān)視,每當 todos 發(fā)生變化就使用本地存儲存儲數(shù)據(jù)。同時初始化的時候,todos 賦值是從本地存儲讀取的
...... <script> ...... export default { ...... data() { return { //讀取本地存儲 todos: JSON.parse(localStorage.getItem("todos")) || [] } }, methods: { ...... }, watch:{ //深度監(jiān)視 todos:{ deep:true, handler(value){ localStorage.setItem("todos",JSON.stringify(value)) } } } } </script> ......
運行程序,輸入數(shù)據(jù),刷新瀏覽器,數(shù)據(jù)不會消失
到此這篇關(guān)于Vue 瀏覽器本地存儲的文章就介紹到這了,更多相關(guān)Vue 瀏覽器本地存儲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁
這篇文章主要為大家介紹了html中引入Vue.js的cdn實現(xiàn)簡單的文檔單頁示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08解決報錯ValidationError: Progress Plugin Invalid&
這篇文章主要介紹了解決報錯ValidationError: Progress Plugin Invalid Options問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11