{products.push({item:"BaseballC">
Suppose I have a simple vue composable function that I want to reuse multiple times throughout my application. In this case, it has a reactive property (products, an array containing a list of products) and a method "addProduct" that pushes new elements to the array.
export function useCart(){ const products = ref([]) const addProduct() =>{ products.push({item: "Baseball Cap", quantity: 1}) } return { products, addProduct } }
It works great. However, I want to pass an instance of the composable cart to each row so that the row can access the parent "cart" via the property "cart".
I hope the following works. I believe "this" should refer to the object on which the function is called (the shopping cart instance):
export function useCart(){ const products = ref([]) const addProduct() =>{ //this should be the instance of the cart composable? products.push({item: "Baseball Cap", quantity: 1, cart: this}) } return { products, addProduct } }
However, when I test in a component using composables, the value of "this" is undefined:
const testCart = useCart testCart.addProduct()
Why is "this" not defined in this context, and how do I access the composable instance inside the composable method?
If you do it right, it will work.
But you must use
functions()
instead oflambda
becauselambda
has no context andthis = window
code>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.