P粉2587888312023-08-30 00:18:04
If you do it right, it will work.
But you must use functions()
instead of lambda
because lambda
has no context and this = window
code>
const addProduct = function() { //this should be the instance of the cart composable? products.value.push({item: "Baseball Cap", quantity: 1, cart: this}) }
But I'm having trouble using the this
context in the .cart attribute.
Similar to cart.products.value[0].cart.products
. It just doesn't work.
I suggest you rethink the design. I won't do that.
Check the playground. The second time is the window.
const { ref } = Vue;
const useCart = function() {
const products = ref([])
const addProduct1 = function() {
//this should be the instance of the cart composable?
products.value.push({item: "Baseball Cap", quantity: 1, cart: this})
}
const addProduct2 = () => {
//this should be the instance of the cart composable?
products.value.push({item: "Baseball Cap", quantity: 1, cart: this})
}
return {
products,
addProduct1,
addProduct2
}
}
const cart = useCart();
cart.addProduct1();
console.log(cart.products.value[0].cart)
cart.addProduct2();
console.log(cart.products.value[1].cart)
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>