Access vue composable instance in function?
P粉845862826
2023-08-29 08:59:18
<p>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. </p>
<pre class="brush:php;toolbar:false;">export function useCart(){
const products = ref([])
const addProduct() =>{
products.push({item: "Baseball Cap", quantity: 1})
}
return {
products,
addProduct
}
}</pre>
<p>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". </p>
<p>I hope the following works. I believe "this" should refer to the object on which the function is called (the shopping cart instance): </p>
<pre class="brush:php;toolbar:false;">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
}
}</pre>
<p>However, when I test in a component using composables, the value of "this" is undefined: </p>
<pre class="brush:php;toolbar:false;">const testCart = useCart
testCart.addProduct()</pre>
<p>Why is "this" not defined in this context, and how do I access the composable instance inside the composable method? </p>
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.