Vue3 / Vuex changing store state doesn’t update computed prop
I work on a ecommerce website build with Vue.js 3 and Django. Currently facing some issues with the cart functionality. I want to update the amount of items inside the cart without reloading the page, so just updating the cart component. For this I set up a Vue app which looks like this:
Vue.js
<li class="nav-item" id="navbar-app"> <a class="nav-link" href="#">Cart ([[ numItems ]])</a> </li> ...js const store = { state: { numItems: {{ cart.get_cart_length }} }, mutations: { increment(state, quantity) { console.log(quantity) state.numItems += quantity } } } const Navbarapp = { delimiters: ['[[', ']]'], store: store, computed: { numItems() { let cart_items = store.state.numItems return cart_items } } } Vue.createApp(Navbarapp).use(store).mount('#navbar-app')
The get_cart_length function just queries the amount of items: cart.py
def get_cart_length(self): return sum(int(item[‘quantity’]) for item in self.cart.values())
If a user adds an item to the cart a fetch function is running. Everything works fine if I update the page I get correct results and correct items so this is not the problem. I tried to trigger the store that the computed prop numItems
will update like this:
(inside the fetch function)
... .then((res) => { this.store.commit('increment', 1) }) ...
this throws an error: Cannot read property 'commit' of undefined
if i refresh the page after adding an item the correct amount is displayed but i want the component to update without refreshing the page. i tried but haven’t found a solution.
Answer
change your store like this:
const store = new Vuex.Store({ // this line changed ... state: { numItems: {{ cart.get_cart_length }} }, mutations: { increment(state, quantity) { console.log(quantity) state.numItems += quantity } } }); // and this line changed ...
and for call your mutation you can use store
without this
keyword (like your computed property)
store.commit('increment', 1)
or with this keyword:
this.$store.commit('increment', 1)