【问题标题】:Add localStorage to Vue JS 2 app将 localStorage 添加到 Vue JS 2 应用程序
【发布时间】:2017-09-25 07:49:14
【问题描述】:

我想在 Vue JS 2 中将 localStorage 添加到我的购物车应用程序中,以便在用户重新加载页面时将商品保存在购物车中,并在用户单击 + 或 - 按钮时保存商品数量。我怎样才能做到这一点?我是 VueJS 的新手。我尝试通过将 itemStorage.fetch() 添加到购物车组件中来解决它,但它不起作用。

这是我目前所拥有的。不幸的是我没有把它分成更小的组件:(

const apiURL = 'https://api.myjson.com/bins/1etx1x';

const STORAGE_KEY = 'vue-js-todo-P7oZi9sL'
let itemStorage = {
  fetch: function() {
    let items = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
    return items;
  },
  save: function(items) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
    console.log('items saved')
  }
}

Vue.filter('addCurrency', val => val.toFixed(2) + ' $');

Vue.component('shopping-cart', {
  props: ['items'],
  data: function() {
    return {
      //item: this.items
      item: itemStorage.fetch()
    };
  },
  watch: {
    items: {
      handler: function(items) {
        itemStorage.save(items);
      }
    }
  },
  computed: {
    total: function() {
      let total = 0;
      this.items.map(item => {
        total += (item.price * item.quantity);
      });
      return total;
    }
  },
  methods: {
    removeItem(index) {
      this.items.splice(index, 1)
    },
    addOne: item => {
      item.quantity++;
    },
    subtractOne: item => {
      item.quantity--;
    },
    removeAll() {
      return this.item.splice(0, this.item.length);
    }
  }
});

const vm = new Vue({
  el: '#shop',
  data: {
    cartItems: [],
    //items: [],
    items: itemStorage.fetch(),
    addToCartBtn: 'Add to cart',
    showCart: false,
    isInCart: 'In cart',
    search: '',
    sortType: 'sort',
    sortOptions: [{
        text: 'choose',
        value: 'sort'
      },
      {
        text: 'name',
        value: 'name'
      },
      {
        text: 'price',
        value: 'price'
      }
    ]
  },
  created: function() {
    this.fetchData();
  },

  computed: {
    products: function() {
      return this.items.filter(item => item.name.toLowerCase().indexOf(this.search.toLowerCase()) >= 0);
    }
  },
  methods: {
    fetchData() {
      axios.get(apiURL)
        .then(resp => {
          this.items = resp.data
        })
        .catch(e => {
          this.errors.push(e)
        })
    },
    sortBy(sortKey) {
      this.items.sort((a, b) =>
        (typeof a[sortKey] === 'string' || typeof b[sortKey] === 'string') ? a[sortKey].localeCompare(b[sortKey]) : a[sortKey] - b[sortKey]);
    },
    toggleCart: function() {
      this.showCart = !this.showCart;
    },
    addToCart(itemToAdd) {
      let found = false;
      this.showCart = true;
      this.cartItems.map(item => {
        if (item.id === itemToAdd.id) {
          found = true;
          item.quantity += itemToAdd.quantity;
        }
      });
      if (found === false) {
        this.cartItems.push(Vue.util.extend({}, itemToAdd));
      }
      itemToAdd.quantity = 1;
    },
    itemInCart(itemInCart) {
      let inCart = false;
      this.cartItems.map(item => {
        if (item.id === itemInCart.id) {
          inCart = true;
        }
      });
      if (inCart === false) {
        return this.isInCart;

      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.16.2/dist/axios.min.js"></script>

【问题讨论】:

    标签: javascript local-storage vuejs2


    【解决方案1】:

    您可以使用 localStorage.getItem() 和 localStorage.setItem(),但根据我使用 localStorage 的经验,它不适用于 Vue。我会遇到各种奇怪的、无法解释的问题。我认为这还不够快。您应该考虑使用 Vuex 并设置 Vuex persisted state 以自动将其同步到会话/本地存储。

    【讨论】:

    • 它不是任何商业项目:我只是想学习,如何使用localstorage与getItem和setIem,最快的方法。没有 vuex 怎么办?只有 get 和 setItem?
    • 我会在“mounted”或“created”上放置一个方法,它使用 getItem 将您的数据设置为 localStorage 值
    【解决方案2】:

    要保持状态,您可以像这样使用插件vue-persistent-state

    import persistentStorage from 'vue-persistent-storage';
    
    const initialState = {
      items: []
    };
    Vue.use(persistentStorage, initialState);
    

    现在items 可用作所有组件和 Vue 实例中的数据。对 this.items 的任何更改都将存储在 localStorage 中,您可以像在普通 Vue 应用中一样使用 this.items

    如果您想了解其工作原理,the code 非常简单。基本上是

    1. 添加 mixin 以使 initialState 在所有 Vue 实例中可用,并且
    2. 监视更改并存储它们。

    免责声明:我是vue-persistent-state的作者。

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2021-11-08
      • 2019-01-22
      • 2021-09-17
      • 2018-07-24
      相关资源
      最近更新 更多