【问题标题】:Return an error message in the form of a toast message to component using Vuex使用 Vuex 以 toast 消息的形式向组件返回错误消息
【发布时间】:2021-07-08 11:55:47
【问题描述】:

我已经使用 Vuex 成功创建了一个购物车,但我还想实现一件事,那就是 toast 消息形式的错误消息。

当用户试图超过产品库存限制时,这将触发。

这是我的代码,看看组件里面的方法,Home.vue

addToCart(product) {
    product.quantity = 1;
    this.$store.commit('addToCart', product)
    this.$store.commit('totalItems');
    this.$store.commit('totalPrice');
}

这一切正常,甚至使用 if 语句来检查用户是否超过限制,到目前为止一切顺利,但这只是我想要显示的消息。

最后,这是我的 store.js 文件:

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
    state: {
        products: [],
        cart: JSON.parse(localStorage.getItem('cart')) ? JSON.parse(localStorage.getItem('cart')) : [],
        totalItems: 0,
        totalPrice: 0,
        newCartItem: {}
    },
    actions: {    
    },
    mutations: {
        // getProducts(state, products) {
        //     state.products = products
        // },
        addToCart ( state, product ) {
            let findProduct = state.cart.find(o => o.id === product.id)
            if( findProduct ) {
                if ( product.quantity + findProduct.quantity > product.units ) {
                    findProduct.quantity = product.units
                    //show message
                } else {
                    findProduct.quantity += product.quantity;
                    findProduct.subtotal = findProduct.quantity * findProduct.price;
                }
            } else {
                state.newCartItem.id = product.id
                state.newCartItem.name = product.name;
                state.newCartItem.price = product.price;
                state.newCartItem.quantity = product.quantity;
                state.newCartItem.image = product.product_image[0].image;
                state.newCartItem.subtotal = product.price;
                state.newCartItem.units = product.units;
                state.cart.push(Object.assign({},state.newCartItem))
                state.newCartItem = {}
            }
            localStorage.setItem('cart', JSON.stringify(state.cart));
        },
        totalItems ( state ) {
            state.totalItems = parseInt(state.cart.reduce((total, item) => {
                return total + item.quantity;
            }, 0))           
        },
        totalPrice ( state ) {
            state.totalPrice = state.cart.reduce((total, item) => {
                return total + item.subtotal;
            }, 0);
        },
        removeFromCart ( state, product ) {
            let findProduct = state.cart.find(o => o.id === product.id)
            if ( findProduct ) {
                state.cart.pop( this.findProduct );
            }  
            localStorage.setItem('cart', JSON.stringify(state.cart));
        },
        changeQuantityItem ( state, product ) {
            let findProduct = state.cart.find(o => o.id === product.id)
            if (findProduct) {
                if ( product.quantity > product.units ) {
                    product.quantity = product.units
                } else {
                    findProduct.quantity = product.quantity;
                }
                findProduct.subtotal = product.quantity * findProduct.price;
            } 
            localStorage.setItem('cart', JSON.stringify(state.cart));
        }
    },
    getters: {
        cart: state => state.cart,
        totalItems: state => state.totalItems,
        totalPrice: state => state.totalPrice
    },
})

我写评论的位置(//show message),我想返回一个toast消息,比如用户不能超过产品的库存。我该怎么做呢?我读过类似你应该使用一个动作的东西,但也许我错了,这可以更容易执行。

任何帮助将不胜感激,在此先感谢!

【问题讨论】:

    标签: vue.js vuejs2 vuex toast


    【解决方案1】:

    你快到了。是的,将其设为 action 仅在您想将其回听到一个组件或其他组件并在发生这种情况时处理某些内容时才有帮助。

    在这种情况下,请使用 Action 方法。

    但是,如果您只想显示消息。您可以使用 [buefy][1] 组件。这甚至在Vue 实例之外也有效。使用起来非常简单。

    import { ToastProgrammatic as Toast } from 'buefy'
    

    像这样使用它:

    //show message
    Toast.open('Item not available.')
    

    如果您担心捆绑包的大小,您甚至可以导入一个组件。 [1]:https://buefy.org/documentation/toast

    【讨论】:

      【解决方案2】:

      因为我使用的是 PrimeVue component library,所以我也想将它用于这些错误消息。这是我为使其工作所做的工作:

      • 我在组件中向计算的错误属性添加了一个函数,如下所示:

          error: function() {
              if (this.$store.state.error !== null ) {
                  this.$toast.add({severity:'warn', summary: 'Warn Message', detail:this.$store.state.error, life: 3000});
                  this.$store.commit('clearError')
              }
              return this.$store.state.error
          }
        

      在我的 store.js 中,我添加了以下代码:

      state.error = "You are trying to exceed the product's available stock."
      

      我只是在消息显示后调用一个函数将 error 属性设置为 null,如下所示:

      clearError ( state ) {
          state.error = null
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-08
        • 2020-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-01
        • 1970-01-01
        • 2011-09-28
        相关资源
        最近更新 更多