Last active
May 30, 2018 11:19
-
-
Save gwuah/c00f73233e9e2b1894730335650a3563 to your computer and use it in GitHub Desktop.
A simple cart store that can be used to persist state across all components and pages. no need VueX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue'; | |
export const Store = new Vue({ | |
data: function () { | |
return { | |
cart: [], | |
tax: 0, | |
totalItemsInCart: 0 | |
} | |
}, | |
methods: { | |
pushToCart: function (product, index) { | |
this.cart.push(product) | |
}, | |
addToCart: function (product) { | |
const element = this.cart.find(el => el.details._id == product._id); | |
if (element) { | |
element.quantity += 1; | |
} else { | |
this.cart.push({ | |
details: product, | |
quantity: 1 | |
}); | |
} | |
}, | |
removeFromCart: function (product) { | |
const index = this.cart.findIndex(el => el.details._id == product._id); | |
if (index > -1) { | |
this.cart.splice(index, 1); | |
} else { | |
console.log("element ain't found"); | |
} | |
}, | |
reduceQuantity: function (product) { | |
const element = this.cart.find(el => el.details._id == product._id); | |
if (element.quantity <= 1) { | |
this.removeFromCart(element.details) | |
} else { | |
element.quantity -= 1; | |
} | |
}, | |
clearCart: function () { | |
this.cart = []; | |
}, | |
getElement: function(id) { | |
return Array.find(el => el.details._id = id) | |
} | |
}, | |
computed: { | |
totalItems: function () { | |
return this.cart.reduce((accum, product) => { | |
return accum + product.quantity | |
}, 0); | |
}, | |
totalCost: function () { | |
return this.cart.reduce((accum, product) => { | |
return accum + (product.details.price * product.quantity) | |
}, 0) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment