{products.push({item:"BaseballC"> Access vue composable instance in function?-PHP Chinese Network Q&A
Access vue composable instance in function?
P粉845862826
P粉845862826 2023-08-29 08:59:18
0
1
509

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?

P粉845862826
P粉845862826

reply all (1)
P粉258788831

If you do it right, it will work.

But you must usefunctions()instead oflambdabecauselambdahas no context andthis = windowcode>

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 thethiscontext in the .cart attribute.

Similar tocart.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)
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!