[Vuejs]-Vuex state not showing empty cart message using v-if & v-else

0👍

Your Vuex getter doesn’t return anything, so it’s always falsy, which makes the computed prop (noItemsInCart) always truthy.

But your getter also isn’t using Array.prototype.filter correctly. The filter is assigning qty instead of comparing it, and the filter callback returns nothing.

I’m guessing you were trying to count the items in the cart by checking productQuantity of each item. That would be done with Array.prototype.some like this:

{
  getters: {
    // find any item that has a positive `productQuantity` value
    cartEmpty: state => state.cart.some(item => item.productQuantity > 0)
  }
}

Also, your template should move the v-for loop into the v-else block. Otherwise, an empty cart will prevent the v-if block from rendering (thus no Cart empty message):

<div v-if="noItemsInCart">Cart empty</div>
<div v-else class="modal-body" v-for="item in this.$store.state.cart">
</div>

0👍

You don’t need getter in this case. You just need to return in computed something like this:

computed: {
  isEmptyCart() {
    return Boolean(~this.$store.state.cart.length); // or use compare ...length > 0
  }.
}

Or more beautiful example with mapState:

computed: {
  ...mapState({
    cart: ({ cart }) => cart; // don't use this.$store.state.cart in template
    isEmptyCart: ({ cart }) => Boolean(~cart.length),
  }),
}

Leave a comment