I am trying to add the items passed from the props to a ref property using a vue-composition API. But, I don't know why the items are not added to the array. Maybe I am using the spread operator in a wrong way or my implementation is wrong but the item is not added.
vue-composition method is in a different file and it is used across the component.
I am passing the props to a product component in this way:
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
Similarly, the product component is setup as:
<template>
<div class="product">
<button type="button" @click="addToCart(item)">Add to Basket</button>
</div>
</template>
<script>
import { useCart } from "../js/ShoppingCart";
export default {
setup(props) {
let item = props;
const { addToCart } = useCart();
return { item, addToCart };
},
props: {
id: Number,
title: String,
image: String,
price: String,
rating: Number,
}
};
</script>
ShoppingCart.js where I am using the @vue-composition-api
import { ref } from "@vue/composition-api";
export function useCart() {
let basket = ref([]);
const addToCart = async (item) => {
// eslint-disable-next-line no-debugger
debugger;
return {
...basket,
item,
};
};
console.log(JSON.stringify(basket));
return { basket, addToCart };
}
I don't know where do I did wrong, the basket array is always empty while calling from different components.
Updated Question:
<template>
<div class="home">
<img
class="home__image"
src="https://images-na.ssl-images-amazon.com/images/G/01/AmazonExports/Fuji/2020/May/Hero/Fuji_TallHero_45M_es_US_2x._CB432534552_.jpg"
/>
<div class="home__row">
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
{{ basket }}
basket length {{ basket.value ? basket.value.length : 0 }}
</div>
</div>
</template>
<script>
// @ is an alias to /src
import Product from "@/components/Product.vue";
import { useCart } from "../js/ShoppingCart";
export default {
setup() {
const { basket } = useCart();
return { basket };
},
name: "Home",
components: {
Product,
},
};
</script>