python - 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
如果我在添加项目后刷新页面,则会显示正确的数量,但我希望组件在不刷新页面的情况下更新。我试过但没有找到解决方案。
解决方案
像这样更改您的商店:
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)
推荐阅读
- c - 为什么我们要使用指针在 C 中存储地址?
- c# - 用于搜索名字和姓氏的第一个字母的正则表达式模式
- c++ - 根据用户输入控制插入到 BST
- arrays - 谷歌表格公式解释
- jenkins - 由 jenkins DSL 配置的 Mutlibranch Pipeline 的问题 - 存储库名称在开头添加了一个不必要的斜杠
- camunda - 重用之前服务任务的会话
- c++ - 什么是'mymap [1];' 说明 mymap 是 std::map 的位置?
- python - 从形状的numpy数组中提取数据()
- python - 如何在python中使用xpath在源代码中获取图像src url
- google-cloud-platform - 如何在 Google Cloud Platform jupyter notebook 中读取 csv 文件