Skip to content

Instantly share code, notes, and snippets.

@c0depanda
Created January 12, 2019 21:29
Show Gist options
  • Save c0depanda/869a1b6df00b940cad26cdba5a82bebf to your computer and use it in GitHub Desktop.
Save c0depanda/869a1b6df00b940cad26cdba5a82bebf to your computer and use it in GitHub Desktop.

Revisions

  1. c0depanda created this gist Jan 12, 2019.
    56 changes: 56 additions & 0 deletions example5.vue
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    <template>
    <main>
    <h1>Cart Content</h1>
    <p>Total Number of Items: {{totalNumberOfCartItems}}</p>
    <form @submit.prevent="addItemToCart">
    <input type="text" v-model="item" required>
    <button type="submit">Add to cart</button>
    </form>

    <button type="button" @click="checkout">Checkout</button>
    </main>
    </template>

    <script>
    export default {
    data() {
    return {
    item: ''
    }
    },
    computed: {
    totalNumberOfCartItems() {
    // Accessing the Vuex state
    return this.$store.getters.totalNumberOfCartItems;
    }
    },
    methods: {
    addItemToCart() {
    // Check that the input field isn't empty
    if(this.item !== '') {
    // commiting the additemtocart mutation with the payload
    this.$store.commit('addItemToCart', this.item)
    }
    },
    checkout() {
    // Make sure cart is not empty
    if(this.totalNumberOfCartItems > 0 ) {
    // create request
    let requestPayload = { cart: this.$store.state.cart };
    // Dispatch the action
    this.$store.dispatch('checkout', requestPayload).then((response) => {
    // Alert Response from API
    alert(response);
    }).catch((error) => {
    // Alert Error from API
    alert(error);
    });
    }
    else {
    alert('Cart is empty');
    }
    }
    }
    }
    </script>