Home > OS >  How to send a parameter to getters in vue?
How to send a parameter to getters in vue?

Time:10-20

I have a getter to check the product stock and amount of the cart. So here is my getters.js:

export const checkStock = (state, productID) => {
    let stockAvailable = true;
    state.cart.forEach(item => {
        if(item.product.id == productID) {
            if(item.product.attributes.stock <= item.amount){
                stockAvailable = false;
            }
        }
    })
    return stockAvailable;
}

So as you see, I am sending productID to this function as a parameter. And then in the Product component, I am calling this function and I want to add productID to this function but I don't know-how.

checkStockAvailability(productId) {
            return this.$store.getters.checkStock;
        },

So how do you think I can add productID to my getters function?

CodePudding user response:

You can use parameters in getters by returning a function that returns the results:

export const checkStock = (state) => (productId) => {
    // call the checkStockAvailability here
    let stockAvailable = true;
    state.cart.forEach(item => {
        if(item.product.id == productID) {
            if(item.product.attributes.stock <= item.amount){
                stockAvailable = false;
            }
        }
    })
    return stockAvailable;
}

// then you can use this getter on the component as

const productId = 2;
store.getters.checkStock(productId)
  • Related