'how can i change state in vuex from a component

I am starting with vuex and i am little bit confused. I want to show a cart when element is clicked in another component(navbar), and cart component will be shown inside home view. Here is my code: Navbar

<img src="../assets/icons/cart-icon.svg" class="icon" @click="$store.commit('customChange')" />

Home

<div v-if="showCartHere">
  <Cart />
</div>
<script>
import Cart from '../components/Cart.vue'

export default {
    name: 'Home',
    components: { Cart },
    data() {
        return {
            showCartHere: false
        }
    },
    mounted() {
        this.showCartHere = this.$store.state.showCart
    }
}
</script>

Store

import { createStore } from 'vuex'

export default createStore({
  state: {
    showCart: false
  },
  getters: {
    showCart: state => {
      return state.showCart
    }
  },
  mutations: {
    customChange(state) {
      return state.showCart = !state.showCart
    }
  },
  actions: {
    customChange({ commit }) {
      commit('customChange')
    }
  },
  modules: {
  }
})


Solution 1:[1]

Component

<template>
  <p v-if="showcart">Show</p>
</template>
<script>
import { mapState } from 'vuex';
computed: (state) => {
  showCart: state.cart.showCart
}
methods: {
  showCartIcon() {
    this.$store.dispatch('cart/show', true)
  }
}
</script>

Now in your module/Cart.js

const state = () => ({
  showCart: false,
})
const actions = {
  show({commit}) {
    commit('showcartMt', true)
  }
}

const mutations = {
  showcartMt(state, toggle) {
    state.showCart = toggle;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandeep