1.使用

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  8. </head>
  9. <body>
  10. <script>
  11. var lists = [{name:"html",state:false}]
  12. // // 将json对象转换为json格式的字符串类型
  13. var res = JSON.stringify(lists);
  14. // // localStorage设置本地存储特点:只能存简单值的类型,不能存数组和对象
  15. localStorage.setItem("todo",res)
  16. // // 取本地存储
  17. var result = localStorage.getItem("todo")
  18. console.log(JSON.parse(result))
  19. var reg = /^[{\[].+[}\]]$/
  20. console.log(reg.test(res))
  21. </script>
  22. </body>
  23. </html>

2.封装使用

封装

  1. // 设置缓存
  2. function setStorage(key, val) {
  3. if (val instanceof Array | typeof value == "Object") {
  4. localStorage.setItem(key, JSON.stringify(val))
  5. } else {
  6. localStorage.setItem(key, val)
  7. }
  8. }
  9. // 获取缓存
  10. function getStorage(key) {
  11. var reg = /^[{\[].+[}\]]$/
  12. let val = localStorage.getItem(key);
  13. if (reg.test(val)) {
  14. return JSON.parse(val)
  15. } else {
  16. return val;
  17. }
  18. // 写正则 [],{}
  19. }

使用封装

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  8. <script src="utils/缓存封装.js"></script>
  9. </head>
  10. <body>
  11. <script>
  12. var lists = [{name:"html",state:false}]
  13. setStorage("todo",lists);
  14. var res = getStorage("todo")
  15. console.log(res)
  16. </script>
  17. </body>
  18. </html>