2017-09-25 5 views
1

Vue JS 2のショッピングカートアプリにlocalStorageを追加して、ユーザーがページをリロードしてアイテムを保存したり、ユーザーが+ボタンまたは - ボタンをクリックしたときにアイテムをカートに保存したい。どうやってやるの?私はVueJSの新作です。ショッピングカートコンポーネントにitemStorage.fetch()を追加して解決しようとしましたが、機能しません。Vue JS 2アプリにlocalStorageを追加する

これはこれまで私が行ってきたことです。残念ながら、私はあなたがlocalStorage.getItemを(使用することができます

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.setItem()、しかし、私の経験でのlocalStorageを使用すると、うまく動作しませんしませんでしたVueのと。私は奇妙な、原因不明の問題のすべての種類を持っているでしょう。私はそれだけで十分な速さではないと思います。あなたが代わりにVuexを使用して、自動的にセッション/ローカルストレージに同期するVuex persisted stateを設定するになっているはずです。

+0

商用プロジェクトではありません。私は、getItemとsetIemでlocalstorageを使用する方法を学びたいだけです。これは最速の方法です。どうすればvuexなしでそれをすることができますか? getとsetItemだけで? – Natalia

+0

getItemを使ってデータをlocalStorageの値に設定する、 "mounted"または "created"にメソッドを配置します –

0

を状態を持続するには、あなたは私たちかもしれませんEこのようなプラグインvue-persistent-state

import persistentStorage from 'vue-persistent-storage'; 

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

itemsは、すべてのコンポーネントとVueのインスタンス内のデータとして利用可能です。 this.itemsへの変更はlocalStorageに保存され、this.itemsはvanilla Vueアプリと同じように使用できます。

この機能の仕組みを理解したい場合は、the codeは非常に簡単です。それは基本的に

  1. すべてのVueのインスタンス、および変更して保存彼らのために
  2. 時計にinitialStateを利用できるようにするmixinを追加します。

免責事項:私はvue-persistent-stateの著者です。

関連する問題