2017-09-25 30 views
1

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

这是我到目前为止。不幸的是我没有把它分割成更小的组件:(

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/[email protected]/dist/axios.min.js"></script>

回答

1

您可以使用localStorage.getItem()和localStorage.setItem(),但在使用localStorage的不顺利我的经验我觉得它的速度不够快,你应该考虑使用Vuex并设置Vuex persisted state来自动将它同步到会话/本地存储。

+0

这不是任何商业项目:我只想学习,如何使用getItem和setIem的localstorage,最快的方法。我如何在没有vuex的情况下做到这一点?只有get和setItem? – Natalia

+0

我会在“挂载”或“创建”方法上使用getItem将您的数据设置为localStorage值 –

0

要保持状态,你可以告诉我们Ë插件vue-persistent-state这样的:

import persistentStorage from 'vue-persistent-storage'; 

const initialState = { 
    items: [] 
}; 
Vue.use(persistentStorage, initialState); 

现在items可在所有组件和Vue的情况下的数据。对this.items的任何更改都将存储在localStorage中,您可以像在vanilla Vue应用程序中那样使用this.items

如果您想了解这是如何工作的,the code非常简单。它基本上

  1. 增加了mixin,使所有Vue的情况下initialState可用,
  2. 表更改并将它们存储。

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