【问题标题】:How to send a parameter to getters in vue?如何向 vue 中的 getter 发送参数?
【发布时间】:2021-12-06 08:53:40
【问题描述】:

我有一个吸气剂来检查购物车的产品库存和数量。所以这是我的 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;
}

如您所见,我将productID 作为参数发送到此函数。然后在 Product 组件中,我正在调用此函数,我想将 productID 添加到此函数中,但我不知道如何操作。

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

那么您认为我可以如何将 productID 添加到我的 getters 函数中?

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex getter


    【解决方案1】:

    您可以通过返回一个返回结果的函数来在 getter 中使用参数:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 2018-02-12
      • 2019-12-29
      • 2012-12-01
      • 2023-03-31
      • 2021-09-21
      • 1970-01-01
      • 2021-03-23
      • 2013-06-18
      相关资源
      最近更新 更多