Last active
February 18, 2023 19:08
-
-
Save nicolasmontielf/edd85318c20650b26baf5b140388aaac to your computer and use it in GitHub Desktop.
Example of a shopping cart component written using the Vue Option API
This file contains 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
<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