Skip to content

Instantly share code, notes, and snippets.

@nicolasmontielf
Last active February 18, 2023 19:08
Show Gist options
  • Save nicolasmontielf/edd85318c20650b26baf5b140388aaac to your computer and use it in GitHub Desktop.
Save nicolasmontielf/edd85318c20650b26baf5b140388aaac to your computer and use it in GitHub Desktop.
Example of a shopping cart component written using the Vue Option API
<template>
<h2>This is the Cart component</h2>
</template>
<script>
import OtherComponent from './OtherComponent.vue'
export default {
components: {
OtherComponent
},
data: () => ({
items: [], // { id, name, price, quantity }
maybeAConstantObject: {
someKey: 'someValue',
anotherKey: 'anotherValue'
}
}),
props: {
userId: {
type: String,
required: true,
},
cartId: {
type: String,
required: true,
},
},
methods: {
addItem: function (item) {
this.items.push(item);
},
removeItem: function (item) {
this.items.splice(this.items.indexOf(item), 1);
},
clear: function () {
this.items = [];
},
proceedToCheckout: function () {
this.$emit('checkout', this.items);
}
},
computed: {
itemsCount: function () {
return this.items.length;
},
total: function () {
return this.items.reduce((total, item) => total +( item.price * item.quantity), 0);
},
isEmpty: function () {
return this.items.length === 0;
},
},
watch: {
items() {
console.log('Cart items changed')
}
},
created() {
console.log('Cart created')
},
mounted() {
fetch('/api/cart/' + this.cartId)
.then(response => response.json())
.then(items => this.items = items)
.catch(error => console.error(error));
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment