美文网首页
vue中封装本地存储方法

vue中封装本地存储方法

作者: w_小伍 | 来源:发表于2020-07-01 10:53 被阅读0次

    在src下新建utils,新建storage.js

    //storage.js
    let ls = window.localStorage
    let ss = window.sessionStorage
    
    export const locStorage = {
      set(name, content) {
        if (!name) return
        ls.setItem(name, JSON.stringify(content))
      },
      get(name) {
        try {
          return JSON.parse(ls.getItem(name))
        } catch (e) {
          return null
        }
      },
      remove(name) {
        if (!name) return
        ls.removeItem(name)
      },
      clear() {
        ls.clear()
      }
    }
    
    export const sesStorage = {
      set(name, content) {
        if (!name) return
        ss.setItem(name, JSON.stringify(content))
      },
      get(name) {
        try {
          return JSON.parse(ss.getItem(name))
        } catch (e) {
          return null
        }
      },
      remove(name) {
        if (!name) return
        ss.removeItem(name)
      },
      clear() {
        ss.clear()
      }
    }
    

    使用
    在使用的页面引入

    import { locStorage } from '@/utils/storage'

    <template>
      <div class="main-wrapper">
        <head-top></head-top>
        <button @click="locStorage()">点击存储</button>
        <button @click="getStorage()">点击获取</button>
      </div>
    </template>
    
    <script>
      import { locStorage } from '@/utils/storage'
      export default {
        name: "localStorage",
        methods:{
          locStorage() {
            let arr1 = [1,'xiaoxi','qq']
            locStorage.set('list',arr1)
          },
          getStorage() {
            let list = locStorage.get('list')
            console.log(list)
          }
        }
      }
    </script>
    
    <style scoped>
    .main-wrapper {
      margin-left: 20px;
    }
    </style>
    
    image.png

    相关文章

      网友评论

          本文标题:vue中封装本地存储方法

          本文链接:https://www.haomeiwen.com/subject/lylcqktx.html