封装存、取storage工具方法

/**
 * 存储localStorage
 */
export const setStorage = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
      content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
  };
  
  /**
   * 获取localStorage
   * 若存的是非字符串则取出来的是字符串,记得JSON.parse还原一下
   */
  export const getStorage = name => {
    if (!name) return;
    return window.localStorage.getItem(name);
  };

使用:

<template>
    <div>
        <div>取数据
            {{geta}},{{getb.k1}},{{getc[1]}}
        </div>
    </div>
</template>

<script>
// 引入存取storage工具方法
import {setStorage,getStorage} from '@/util/util'
// 在外面定义变量 vue内部能否访问
// let bian = 'husdb' //可以访问,scrupt标签内定义的是全局变量。

export default {
    data() {
        return {
          a:'12',   //字符串
          b:{k1:1,k2:2},  //对象
          c:[1,2,3],  //数组
        }
    },
    computed: {
        geta(){
           return getStorage('a') 
        },
        getb(){
           return JSON.parse(getStorage('b')) 
        },
        getc(){
           return JSON.parse(getStorage('c')) 
        },
    },
    created() {
        // console.log(bian)
        setStorage('a',this.a)
        setStorage('b',this.b)
        setStorage('c',this.c)
    },
}
</script>

 

posted @ 2020-08-22 15:33  伟笑  阅读(382)  评论(0编辑  收藏  举报