赞
踩
1.localStorage 属性是只读的。
2.localStorage 和 sessionStorage 属性允许在浏览器中存储 key/value 对的数据。
3.localStorage 用于长久保存整个网站的数据, 保存的数据没有过期时间, 直到手动去删除。
4.如果只想将数据保存在当前会话中,可以使用 sessionStorage 属性, 该数据对象临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。
保存数据
localStorage.setItem("key", "value");
读取数据
let value = localStorage.getItem("key");
删除数据
localStorage.removeItem("key");
新建local.js文件
- class LocalCache {
- // localStorage 的存储
- setCath(key, value) {
- window.localStorage.setItem(key, JSON.stringify(value));
- }
-
- // localStorage 的读取
- getCache(key) {
- // obj=>sting=>obj
- const value = window.localStorage.getItem(key);
- try {
- return JSON.parse(window.localStorage.getItem(key));
- } catch (error) {
- return value;
- }
- }
-
- // localStorage 的删除
- deleteCatch(key) {
- window.localStorage.removeItem(key);
- }
-
- // 删除所有的 localStorage
- clearCache() {
- window.localStorage.clear();
- }
- }
-
- export default new LocalCache();
先引入封装好的文件
import LocalCache from '@/utils/local'
- !
- <template>
- <div></div>
- </template>
-
- <script>
- import LocalCache from '@/utils/local'
- export default {
- name: 'Dashboard',
- components: {},
- props: {},
- data() {
- return {
- userInfo: {},
- }
- },
- computed: {},
- watch: {},
- created() {
- //读取本地缓存
- let userInfo = LocalCache.getCache('userInfo')
- console.log(userInfo, 'userInfo++++++++++++++')
-
- //保存本地缓存
- LocalCache.setCath('userInfo', this.userInfo)
-
- //删除本地缓存
- LocalCache.deleteCatch('userInfo')
- },
- mounted() {},
- methods: {},
- }
- </script>
-
- <style lang="scss"></style>
- // localStorage 的存储
- export const setCath = (key, value) => {
- window.localStorage.setItem(key, JSON.stringify(value));
- };
-
- // localStorage 的读取
- export const getCache = (key) => {
- const value = window.localStorage.getItem(key);
- try {
- return JSON.parse(window.localStorage.getItem(key));
- } catch (error) {
- return value;
- }
- };
-
- // localStorage 的删除
- export const deleteCatch = (key) => {
- window.localStorage.removeItem(key);
- };
-
- // 删除所有的 localStorage
- export const clearCache = () => {
- window.localStorage.clear();
- };
先引入封装好的文件
import { setCath, getCache, deleteCatch } from '@/utils/local'
- !
- <template>
- <div></div>
- </template>
-
- <script>
- import { setCath, getCache, deleteCatch } from '@/utils/local'
- export default {
- name: 'Dashboard',
- components: {},
- props: {},
- data() {
- return {
- userInfo: {},
- }
- },
- computed: {},
- watch: {},
- created() {
- setCath('userInfo',this.userInfo)
-
- let userInfo = getCache('userInfo')
- console.log(userInfo,'userInfo+++')
-
- deleteCatch('userInfo')
- },
- mounted() {},
- methods: {},
- }
- </script>
-
- <style lang="scss"></style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。