H5之后,前端存储从之前的 cookies 又新增了, localStorage 和 sessionStrage 这两者的区别呢,就是一个本地持久化和一个内存存储的区别。操作没有区别

组件代码
 export default {
    name: 'SearchSimilar',
    props: {
        log: {
          type: String,
          default: 'log'
        },
        doValue: {
          type: String,
          default: ''
        }
    },
    data(){
      return {
          logs: [],
          saveType: 'local'
      }
    },
    watch: {
       doValue(val) {
          if(!this.logs){
            this.logs = [];
          }
          this.logs.unshift(val)
          this.todo(this.log, JSON.stringify(this.logs))
       }
    },
    mounted(){
        this.saveType = window.localStorage ? 'local' : 'cookies'
        if(this.saveType === 'local'){
            let log = localStorage.getItem(this.log);
            this.logs = JSON.parse(log);
        }else{
            //退而求其次,使用cookies来存储
            let log = this.getCookies(this.log);
            this.logs = JSON.parse(log);
        }
    },
    methods:{
      getCookies(field = ''){
          let cookieArray = document.cookie; 
          let arr = cookieArray.split(";"); 
          let max = arr.length;
          let cookiesArr = {}
          if(max > 0){
              for(let i=0; i<max; i++){
                let [key, value] = arr[i].split("=");
               cookiesArr[key] = value
              }
          }
          if(field){
            return cookiesArr[field]
          }else{
            return cookiesArr;
          }

      },

      choose(item){
        this.$emit("choose", item)
      },

      setCookies(name, item){
          let d = new Date();
              d.setTime(d.getTime() + (30*24*60*60*1000));
          let expires = "expires="+ d.toUTCString();
          document.cookie = name + "=" + item + ";" + expires + ";path=/";
      },

      del(item){
        this.logs = this.logs.filter( v => {
          return v !== item
        })

        this.todo(this.log, JSON.stringify(this.logs))
      },

      delAll(){
        this.logs = [];
        this.todo(this.log, "")
      },

      todo(name,value){
        if(this.saveType === 'local'){
          localStorage.setItem(name, value)
        }else{
          this.setCookies(name, value);
        }  
      }
    }
} 

逻辑就是,先判断游览器是否支持 localStorage ,不支持就走cookies存储。然后再加两个操作方法。

localStorage 存储效果图
前端业务展示效果图

Leave a Reply

Your email address will not be published. Required fields are marked *