在vue中優雅的使用LocalStrong


h5的LocalStrong幫我們緩存一些數據到本地,最常用的使用場景,比如京東購物在未登陸的狀態下,把商品加入購物車,收藏某個商品。當我們把url復制到另外一個瀏覽器,購物車就是空的。

以下是一個簡單的商品收藏小demo,讓我們在未登陸的狀態下收藏某個商品。這個例子是學習vue時,看了仿餓了么教程,並把它提取出來,已做備用。

stroe.js:

// 此函數用來緩存數據
export function saveToLocal(id, key, value) {
    // 創建儲存對象
    let seller = window.localStorage.__seller__;
    if (!seller) {
        seller = {};
        // 通過id向__seller__添加一個空緩存對象
        seller[id] = {};
    } else {
        // eg: JSON.parse('{"1":"123","2":"456"}') 
        // result: {1:"123",2:"456"}
        seller = JSON.parse(seller);
        if (!seller[id]) {
            seller[id] = {};
        }
    }
    seller[id][key] = value;
    // localStorage只能存儲字符串
    // eg: JSON.stringify({1:"123",2:"456"}) 
    // result: "{"1":"123","2":"456"}"
    window.localStorage.__seller__ = JSON.stringify(seller);
};

// 此函數返回一個布爾值
export function loadFromLocal(id, key, def) {
    let seller = window.localStorage.__seller__;
    // 默認值
    if (!seller) {
        return def;
    }
    // 從id下獲取緩存的對象
    seller = JSON.parse(seller)[id];
    if (!seller) {
        return def;
    }
    let ret = seller[key];
    return ret || def;
};

使用方法:

<tempalte>
  <div class="favorite" @click="toggleFavorite">
    <span :class="{'active':favorite}"></span>
  </div>
</tempalte>
<script>
import {saveToLocal, loadFromLocal} from 'store.js';
export default {
  // 父組件傳過來一個id
  props: ['id'],
  data() {
    return {
      favorite: (() => {
        // 返回該id下 key為favorite的所對應的value,默認為false
        return loadFromLocal(this.id, 'favorite', false);
      })()
    }
  }
  methods: {
    toggleFavorite() {
      this.favorite = !this.favorite;
      // 把該id下 key為favorite的所對應的value 緩存起來
      saveToLocal(this.id, 'favorite', this.favorite);
    }
  }
}
</script>
<style>
.active {
  color: red;
}
</style>

代碼加了注釋

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM