Skip to content

Instantly share code, notes, and snippets.

@nicolasmontielf
Created February 18, 2023 19:09
Show Gist options
  • Save nicolasmontielf/49b80af5b78d0801069b746f7d57d858 to your computer and use it in GitHub Desktop.
Save nicolasmontielf/49b80af5b78d0801069b746f7d57d858 to your computer and use it in GitHub Desktop.
Example of a shopping cart component written using the Vue Composition API
<template>
<h3>Cart component</h3>
<OtherComponent />
</template>
<script setup>
import OtherComponent from './OtherComponent.vue'
import { computed, ref, watch, onMounted } from 'vue'
const props = defineProps({
userId: {
type: String,
required: true,
},
cartId: {
type: String,
required: true,
},
})
const emit = defineEmits(['checkout'])
const items = ref([]) // { id, name, price, quantity }
const maybeAConstantObject = {
someKey: 'someValue',
anotherKey: 'anotherValue'
}
function addItem(item) {
items.value.push(item);
}
function removeItem(item) {
items.value.splice(items.indexOf(item), 1);
}
function clear() {
items.value = [];
}
function proceedToCheckout() {
emit('checkout', items.value);
}
const itemsCount = computed(() => {
return items.value.length;
})
const total = computed(() => {
return items.value.reduce((total, item) => total +(item.price * item.quantity), 0);
})
const isEmpty = computed(() => {
return items.length === 0;
})
watch(items, () => {
console.log('Cart items changed')
}),
// Created
console.log('Cart created')
onMounted(() => {
fetch('/api/cart/' + props.cartId)
.then(response => response.json())
.then(items => items.value = 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