【问题标题】:Vue3 / Vuex changing store state doesn't update computed propVue3 / Vuex 更改存储状态不会更新计算道具
【发布时间】:2021-07-09 18:14:37
【问题描述】:

我在一个使用 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

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

【问题讨论】:

    标签: python django vue.js fetch vuex


    【解决方案1】:

    像这样改变你的商店:

    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)
    

    【讨论】:

    • 我现在尝试了这个我收到错误“Vue.mixin 不是函数”。我导入了 vuex.js 版本 3.6.2 和 vue.global.min.js 版本 3.0.11
    • 你不能使用Vuex3 代替Vue3 你应该使用vuex4 代替Vue3 : next.vuex.vuejs.org/installation.html
    • 哦,好吧,不知道。现在您的解决方案有效:) 感谢您的帮助!
    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2016-12-13
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多