浏览器存储 (webStorage)
浏览器存储(webStorage)
存储内容不是 Vue 团队打造的,原本的 js 中就有,所以可以不适用脚手架编译,可以写在 HTML 中
webStorage 又分为 localStorage 和 sessionStorage,浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
存储内容大小一般支持 5MB 左右(不同浏览器可能还不一样),它的键值对都是字符串
下面通过一个常见的应用案例来解释说明
1 浏览器本地存储应用
浏览器本地存储应用就是在本地浏览器中缓存些东西到硬盘中
下面以唯品会为例子演示,搜索框输入皮鞋,回车搜索

关闭页面,再次打开网页,发现皮鞋存在了搜索历史中
这里我是没有登录的,所以不可能是存入到数据库,浏览器本地存储是存储到硬盘的

通过控制的 Application 的 LocalStorage 中可以看到

可以看到是以键值对的形式存储的
如果我们新增一个,可以看到搜索历史中又多了一个

点击❌则会清空

这就是浏览器本地存储应用,我们也是可以通过代码实现类似的功能,下面进行演示
2 localStorage(本地存储)
localStorage 的最大特点就是就算把浏览器关闭掉也不会消息。如果想把清除它,可以清除缓存
可以通过 JS 控制 ocalStorage 的 crud,编写几个按钮,分别对 localStorage 里面的数据进行 crud
新增字符串
使用 window.localStorage.setItem('xxx','xxx')方法即可新增,是键值对的形式,window 可写可不写
注意:键和值必须都是字符串,如果不是字符串,会默认调用 toString()方法


新增对象
如果新增的不是一个字符串,而是一个对象呢,如果直接新增的话,肯定会被 toString


所以要使用 JSON.stringify 格式化处理下


这样新增的时候就可以新增一个字符串和一个对象了


读取字符串
既然设置(新增)使用的是 setItem,那么读取肯定就是 getItem 了,根据 key 读取,有返回值


读取对象
上面读取对象的格式不是我们想要的,我们需要解析一下


如果读取字符串的是 key 不存在,那么则显示 null
如果读取对象的 key 不存在,那么也显示 null
删除
使用的 api 是 removeItem,根据 key 删除 localStorage 中的数据


清空
和删除类似,删除是根据 key 删除单个,但是清空会删除全部的,这个 api 是 clear


代码如下
到了这里 localStorage 的应用和查看方式以及简单 crud 就说完了,localStorage 的最大特点就是就算把浏览器关闭掉也不会消息,下面介绍 sessionStorage
3 sessionStorage(会话存储)
localStorage 有一个弟弟叫 sessionStorage,它的特点就是浏览器已关闭,数据就没了
localStorage 的所有 API 都可以适用于 sessionStorage

既然 localStorage 的所有 API 都可以适用于 sessionStorage,那么就可以复制刚才 localStorage 的代码进行简单修改
注意:使用 sessionStorage 的 API 要把 localStorage 进行替换

功能都是一样的,就不贴图了,而且关闭浏览器重新打开后,数据会消失
4 总结
相关 API:
xxxxxStorage.setItem('key', 'value'); 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
2.xxxxxStorage.getItem('person'); 该方法接受一个键名作为参数,返回键名对应的值。
xxxxxStorage.removeItem('key');该方法接受一个键名作为参数,并把该键名从存储中删除。
xxxxxStorage.clear()该方法会清空存储中的所有数据。
备注:
SessionStorage 存储的内容会随着浏览器窗口关闭而消失。
LocalStorage 存储的内容,需要手动清除才会消失。
xxxxxStorage.getItem(xxx)如果 xxx 对应的 value 获取不到,那么 getItem 的返回值是 null。
JSON.parse(null)的结果依然是 null。
评论