首页 > 解决方案 > Vue3 / Vuex 更改存储状态不会更新计算道具

问题描述

我在一个使用 Vue.js 3 和 Django 构建的电子商务网站上工作。目前面临购物车功能的一些问题。我想在不重新加载页面的情况下更新购物车内的商品数量,所以只需更新购物车组件。为此,我设置了一个 Vue 应用程序,如下所示:

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')

get_cart_length 函数只查询商品数量:cart.py

def get_cart_length(self): return sum(int(item['quantity']) for item in self.cart.values())

如果用户将商品添加到购物车,则获取功能正在运行。如果我更新页面,一切正常,我得到正确的结果和正确的项目,所以这不是问题。我试图触发计算道具numItems将像这样更新的商店:(在 fetch 函数内部)

...
.then((res) => {
   this.store.commit('increment', 1)
})
...

这会引发错误Cannot read property 'commit' of undefined

如果我在添加项目后刷新页面,则会显示正确的数量,但我希望组件在不刷新页面的情况下更新。我试过但没有找到解决方案。

标签: pythondjangovue.jsfetchvuex

解决方案


像这样更改您的商店:

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 ...

并调用你的突变,你可以使用store没有this关键字(比如你​​的计算属性)

store.commit('increment', 1)

或使用此关键字:

this.$store.commit('increment', 1)

推荐阅读